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
955
F
Heaps
You're given a tree with $n$ vertices rooted at $1$. We say that there's a $k$-ary heap of depth $m$ located at $u$ if the following holds: - For $m = 1$ $u$ itself is a $k$-ary heap of depth $1$. - For $m > 1$ vertex $u$ is a $k$-ary heap of depth $m$ if \textbf{at least} $k$ of its children are $k$-ary heaps of depth \textbf{at least} $m - 1$. Denote $dp_{k}(u)$ as maximum depth of $k$-ary heap in the subtree of $u$ (including $u$). Your goal is to compute $\sum_{k=1}^{n}\sum_{u=1}^{n}d p_{k}(u)$.
Denote $heap_{k}(u)$ as maximum depth of $k$-ary heap rooted at $u$, and $dp_{k}(u)$ as maximum depth of $k$-ary heap in the subtree of $u$ (including $u$). Let $v_{i}$ - children of vertex $u$; sort them in order of descending $heap_{k}{v_{i}}$. Then $heap_{k}(u) = heap_{k}(v_{k}) + 1$, and $dp_{k}(u) = max(heap_{k}(u), max_{j}(dp_{k}(v_{j})))$. So we can calculate dp for fixed $k$ in $O(n\log n)$ or in $O(n)$, if we will use $nth_element$, so we can solve the problem in $O(n^{2})$. For simplicity, denote $dp_{k}(1)$ as $p_{k}$. Let's suppose that $k > 1$. Note three facts: $p_{k} \le log_{k}(n)$; $dp_{k}(u) \le 2$ when $k\geq{\sqrt{n}}$. $heap_{k}(u) \ge heap_{k + 1}(u)$. So we can solve the problem in $O(n{\sqrt{n}})$. Let's solve task in $O(n)$ when $k\leq{\sqrt{n}}$. For other $k$'s let's go in descending order, and set the value of dp to $2$ and push this value up to the root for each vertices, that have exactly $k$ children. Note, that the total number of vertices visited in pushes does not exceed $n$ (Because if we arrive at vertex with $dp = 2$, it is useless to go up, because everything there has already been updated. Each vertex will be added exactly one time, so complexity of this part is $O(n)$. Let's use this idea to solve the problem in $n^{\frac{1}{3}}$. For each $k\leq n^{{\frac{1}{3}}}$ let's solve in $O(n)$, and for $k\geq{\sqrt{n}}$ let's use the idea above. And when $n^{\frac{1}{3}}\leq k\leq{\sqrt{n}}$, $dp_{k}(u)$ does not exceed $3$. Let $f_{3}(u)$ will be minimal $k$, such that $heap_{k}(u)$ is equal to $3$. By definition, $u$ will have at least $k$ children, which are the heaps of depth 2, that is also vertices with at least $k$ children. Let's sort $v$ by number of their children; Then answer for $u$ will be maximal $k$, such that $children(v_{k}) \ge k$. Let's precalculate it, and when let's go in descending order by $k$ pushing up value $3$ from each $u$ with $f_{3}(u) = k$. The total number of vertices visited in pushes does not exceed $2 \cdot n$ (At worst case, in each vertex will be pushed at first with value $2$, and then with value $3$). So we can solve the problem in $O(n^{\frac{1}{3}})$, which is better but still not enough. Let $val(u, depth)$ - maximal $k > 1$, such that vertex $u$ contain $k$-ary heap of depth $depth$ (or $- 1$, if there are no such vertex). This dp have $n\log n$ states; To recalculate $val(u, depth)$ we need to sort $val(v_{i}, depth - 1)$ by descending order, and find maximal $k$, such that $val(v_{k}, depth - 1) \ge k$. So, with sort, complexity of this solution will be $O(n\log^{2}n)$. Let's go in descending order by $k$ pushing up value $x$ from each $u$ with $val(u, x) = k$. The total number of vertices visited in pushes does not exceed $n \cdot logn$ because $dp_{k}(u) \le log_{k}(n)$. So, the complexity of this solution wil be $O(n\log n)$.
[ "dp", "trees" ]
2,600
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <vector> #include <ctime> #include <unordered_set> #include <string> #include <map> #include <unordered_map> #include <random> #include <set> #include <cassert> #include <functional> #include <queue> #include <numeric> #include <bitset> using namespace std; const int N = 300500, M = 20; mt19937 gen(time(NULL)); #define forn(i, n) for (int i = 0; i < n; i++) #define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define all(a) (a).begin(), (a).end() #define pii pair<int, int> #define mp make_pair #define endl '\n' typedef long long ll; template<typename T = int> inline T read() { T val = 0, sign = 1; char ch; for (ch = getchar(); ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') sign = -1; for (; ch >= '0' && ch <= '9'; ch = getchar()) val = val * 10 + ch - '0'; return sign * val; } vector<int> g[N]; vector<int> children[N]; int p[N], ch[N]; int dp[N][M], n; void dfs_init(int u, int e) { p[u] = e; for (const int &v : g[u]) if (v != e) { ch[u]++; dfs_init(v, u); children[u].push_back(v); } } vector<pii> up[N]; int val[N]; int vis = 0; void dfs(int u) { for (const int &v : children[u]) dfs(v); auto &_dp = dp[u]; _dp[1] = n; for (int k = 2; k < M; k++) { vector<int> heaps; for (const int &v : children[u]) if (dp[v][k - 1] != -1) heaps.push_back(dp[v][k - 1]); sort(all(heaps), greater<int>()); for (int sz = (int)heaps.size() - 1; sz > 0; sz--) if (heaps[sz] >= sz + 1) { _dp[k] = sz + 1; break; } if (_dp[k] != -1) up[_dp[k]].emplace_back(u, k), vis++; } } ll ans = 0; int dfs_one(int u) { if (!ch[u]) { ans++; return 1; } int mx = 0; for (const int &v : children[u]) mx = max(mx, dfs_one(v)); ans += mx + 1; return mx + 1; } void solve() { n = read(); forn(i, n - 1) { int u = read(), v = read(); g[u].push_back(v); g[v].push_back(u); } dfs_init(1, -1); fill_n(&dp[0][0], N * M, -1); dfs(1); dfs_one(1); ll add = n; fill_n(val, N, 1); fprintf(stderr, "%d\n", vis); for (int k = n; k > 1; k--) { for (const auto &Q : up[k]) { int u = Q.first, v = Q.second; for (; u != -1 && val[u] < v; u = p[u]) add += v - val[u], val[u] = v; } ans += add; } printf("%lld\n", ans); } void precalc() { } signed main() { int t = 1; precalc(); while (t--) { clock_t z = clock(); solve(); debug("Total Time: %.3f\n", (double)(clock() - z) / CLOCKS_PER_SEC); } }
957
A
Tritonic Iridescence
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas. Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into $n$ consecutive segments, each segment needs to be painted in one of the colours. Arkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.
The problem can be solved in different approaches. Here we describe one based on manually finding out all cases. What causes the answer to be "Yes"? Of course, there cannot be adjacent segments that already have the same colour; but what else? We can figure out that whenever two consecutive question marks appear, there are at least two ways to fill them. But the samples lead us to ponder over cases with one single question mark: a question mark can be coloured in two different colours if it lies on the boundary of the canvas, or is between two adjacent segments of the same colour. Putting it all together, we get a simple but correct solution. There surely are dynamic programming solutions to this problem, and if you'd like a harder version, try this USACO problem. So to me seems like a notorious coincidence ._.
[ "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; void NO() { puts("No"); exit(0); } void YES() { puts("Yes"); exit(0); } int main() { int n; cin >> n; string s; cin >> s; for(int i = 0; i < n - 1; ++i) if(s[i] != '?' && s[i] == s[i+1]) NO(); for(int i = 0; i < n; ++i) if(s[i] == '?') { if(i == 0 || i == n - 1) YES(); if(s[i+1] == '?') YES(); if(s[i-1] == s[i+1]) YES(); } NO(); }
959
A
Mahmoud and Ehab and the even-odd game
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer $n$ and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer $a$ and subtract it from $n$ such that: - $1 ≤ a ≤ n$. - If it's Mahmoud's turn, $a$ has to be even, but if it's Ehab's turn, $a$ has to be odd. If the current player can't choose any number satisfying the conditions, he loses. Can you determine the winner if they both play optimally?
It's easy to see that if $n = 0$, the next player loses. If $n$ is even, Mahmoud will choose $a = n$ and win. Otherwise, Mahmoud will have to choose $a < n$. $n$ is odd and $a$ is even, so $n - a$ is odd. Ehab will then subtract it all and win. Therefore, if $n$ is even Mahmoud wins. Otherwise, Ehab wins. $n = 1$ doesn't follow our proof, yet Ehab still wins at it because Mahmoud won't be even able to choose $a$. Time complexity : $O(1)$.
[ "games", "math" ]
800
"#include <iostream>\nusing namespace std;\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tif (n%2)\n\tprintf(\"Ehab\");\n\telse\n\tprintf(\"Mahmoud\");\n}"
959
B
Mahmoud and Ehab and the message
Mahmoud wants to send a message to his friend Ehab. Their language consists of $n$ words numbered from $1$ to $n$. Some words have the same meaning so there are $k$ groups of words such that all the words in some group have the same meaning. Mahmoud knows that the $i$-th word can be sent with cost $a_{i}$. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message? The cost of sending the message is the sum of the costs of sending every word in it.
It's easy to see that for every word, the minimum cost of sending it is the minimum cost of sending any word in its group. For each group, we'll maintain the minimum cost for sending a word in it (let it be $cost_{i}$) and for each word, we'll maintain its group (let it be $group_{i}$). For every word $i$ in the message, we'll add $cost_{groupi}$ to the answer. Time complexity : $O((n + m)log(n) * len)$.
[ "dsu", "greedy", "implementation" ]
1,200
"#include <iostream>\n#include <map>\nusing namespace std;\nmap<string,int> d;\nint arr[100005],cost[100005],group[100005];\nint main()\n{\n\tint n,k,m;\n\tcin >> n >> k >> m;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\td[s]=i;\n\t}\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tcin >> arr[i];\n\t\tcost[i]=(1<<30);\n\t}\n\tfor (int i=1;i<=k;i++)\n\t{\n\t\tint x;\n\t\tcin >> x;\n\t\twhile (x--)\n\t\t{\n\t\t\tint a;\n\t\t\tcin >> a;\n\t\t\tgroup[a]=i;\n\t\t\tcost[i]=min(cost[i],arr[a]);\n\t\t}\n\t}\n\tlong long ans=0;\n\twhile (m--)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\tans+=cost[group[d[s]]];\n\t}\n\tcout << ans;\n}"
959
C
Mahmoud and Ehab and the wrong algorithm
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is: Given an undirected tree consisting of $n$ nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge $(u, v)$ that belongs to the tree, either $u$ is in the set, or $v$ is in the set, \textbf{or both are in the set}. Mahmoud has found the following algorithm: - Root the tree at node $1$. - Count the number of nodes at an even depth. Let it be $evenCnt$. - Count the number of nodes at an odd depth. Let it be $oddCnt$. - The answer is the minimum between $evenCnt$ and $oddCnt$. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0. Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of $n$ nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.
For $n \ge 6$, you can connect nodes $2$, $3$, and $4$ to node $1$ and connect the rest of the nodes to node $2$. The real vertex cover is the set ${1, 2}$ of size $2$ while the found vertex cover will have size $min(3, n - 3)$. As $n \ge 6$, that value will be $3$ which is incorrect. For $n < 6$, the answer doesn't exist. There are multiple ways to construct it. One easy way is the star tree. Connect all the nodes to node $1$. The real and the found vertex cover will be simply ${1}$. Another easy way is a path. Connect node $i$ to node $i + 1$ for all $1 \le i < n$. The real and the found vertex cover has size $\lfloor{\frac{n}{2}}\rfloor$. Time complexity : $O(n)$.
[ "constructive algorithms", "trees" ]
1,500
"#include <iostream>\nusing namespace std;\nint main()\n{\n\tint n;\n\tcin >> n;\n\tif (n<=5)\n\tputs(\"-1\");\n\telse\n\t{\n\t\tfor (int i=2;i<=4;i++)\n\t\tprintf(\"1 %d\\n\",i);\n\t\tfor (int i=5;i<=n;i++)\n\t\tprintf(\"2 %d\\n\",i);\n\t}\n\tfor (int i=2;i<=n;i++)\n\tprintf(\"1 %d\\n\",i);\n}"
959
D
Mahmoud and Ehab and another array construction task
Mahmoud has an array $a$ consisting of $n$ integers. He asked Ehab to find another array $b$ \textbf{of the same length} such that: - $b$ is lexicographically greater than or equal to $a$. - $b_{i} ≥ 2$. - $b$ is pairwise coprime: for every $1 ≤ i < j ≤ n$, $b_{i}$ and $b_{j}$ are coprime, i. e. $GCD(b_{i}, b_{j}) = 1$, where $GCD(w, z)$ is the greatest common divisor of $w$ and $z$. Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it? An array $x$ is lexicographically greater than an array $y$ if there exists an index $i$ such than $x_{i} > y_{i}$ and $x_{j} = y_{j}$ for all $1 ≤ j < i$. An array $x$ is equal to an array $y$ if $x_{i} = y_{i}$ for all $1 ≤ i ≤ n$.
Common things : Let's call a number "ok" if it could be inserted to array $b$, as a new element, without breaking any of the conditions (i.e it should be coprime with all the previously inserted elements). Let's call the maximum number that could be inserted in the worst case $mx$. For each integer from 2 to $mx$, we'll precompute its prime divisors with sieve. Create an std::set that contains all the numbers from $2$ to $mx$. That set has all the "ok" numbers and will be updated each time we insert a new element to array $b$. We'll insert the elements to array $b$ greedily one by one. At index $i$, let $cur$ be the minimum number in the set greater than or equal to $a_{i}$ i.e std::lower_bound(a[i]). If cur isn't equal to $a_{i}$, the lexicographically greater condition is satisfied and we're no longer restricted to $a$, so, starting from index $i + 1$, we'll greedily choose $cur$ to be the first (minimum) number in the set instead. We'll insert $cur$ to $b$. Each time, we'll remove all the integers that aren't coprime with $cur$ from the set. To do that, we'll loop over the multiples of its precomputed prime divisors and remove them from the set. Let $used[i]$ indicate whether some prime is already a factor of one of elements in $b$ (so we shouldn't use it). Each time we insert an element to $b$, we update $used$ by iterating over its precomputed prime divisors and make them all used. We'll start inserting elements to $b$ greedily one by one. To check if a number is "ok", we'll iterate over its precomputed prime divisors and check that all of them aren't used. While $a_{i}$ is "ok", we'll keep inserting it to $b$. We'll reach an integer that isn't "ok". In this case, we'll iterate naiively until we find an integer that is "ok" and insert it to $b$. The lexicographically greater condition is now satisfied and we can insert whatever we want (no restriction to $a$). Notice that starting from now, $b$ will be sorted in increasing order. That's because if it's not, we can sort it and reach a better answer without breaking any of the conditions. The naiive solution is to loop starting from 2 until we find an "ok" integer for each $i$. However, as the array is sorted, we can loop starting from 2 the first time and then loop starting from $b_{i - 1} + 1$ and save a lot of loops that we're sure will fail! Time complexity : $O(mxlog(mx))$. $mx$ has an order of $\begin{array}{c l c r}{{\displaystyle{\cal{O}}\displaystyle{\left((n+\frac{m a x A i}{l o q(m a x A i)}}\right)l o g\displaystyle(n+\frac{m a x A i}{l o q(m a x A i)}}\bigg)\bigg)}}\end{array}$ because the $n^{th}$ prime is expected to be $O(nlog(n))$ and the number of primes less that $n$ is expected to be $O(\underline{{{i m}}}_{o p(n)}^{n})$.
[ "constructive algorithms", "greedy", "math", "number theory" ]
1,900
"#include <iostream>\n#include <vector>\nusing namespace std;\nvector<int> d[2000005];\nbool p[2000005],used[2000005];\nbool ok(int x)\n{\n\tbool ret=1;\n\tfor (int i:d[x])\n\tret&=!used[i];\n\treturn ret;\n}\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor (int i=2;i<2000005;i++)\n\t{\n\t\tif (!p[i])\n\t\t{\n\t\t\tfor (int x=i;x<2000005;x+=i)\n\t\t\t{\n\t\t\t\td[x].push_back(i);\n\t\t\t\tp[x]=1;\n\t\t\t}\n\t\t}\n\t}\n\tbool eq=1;\n\tint cur=2;\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tint a;\n\t\tscanf(\"%d\",&a);\n\t\tint out=a;\n\t\tif (eq)\n\t\t{\n\t\t\twhile (!ok(out))\n\t\t\tout++;\n\t\t\tif (out!=a)\n\t\t\teq=0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile (!ok(cur))\n\t\t\tcur++;\n\t\t\tout=cur;\n\t\t}\n\t\tprintf(\"%d \",out);\n\t\tfor (int x:d[out])\n\t\tused[x]=1;\n\t}\n}"
959
E
Mahmoud and Ehab and the xor-MST
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of $n$ vertices numbered from $0$ to $n - 1$. For all $0 ≤ u < v < n$, vertex $u$ and vertex $v$ are connected with an undirected edge that has weight $u\oplus v$ (where $\mathbb{C}$ is the bitwise-xor operation). Can you find the weight of the minimum spanning tree of that graph? You can read about complete graphs in https://en.wikipedia.org/wiki/Complete_graph You can read about the minimum spanning tree in https://en.wikipedia.org/wiki/Minimum_spanning_tree The weight of the minimum spanning tree is the sum of the weights on the edges included in it.
For convenience, let $n$ be the label of the last node not the number of nodes (i.e $n = n_{input} - 1$). Denote $lsb(x) = x&( - x)$ as the value of the least significant bit set to 1 in $x$. The answer is $\sum_{i=1}^{n}l s b(i)$, which means that node $u$ is connected to node $u\oplus l s b(u)$ for all $1 \le u \le n$ (node $u$ is connected to node $u$ without that bit). Let's take a look at a version of Boruvka's algorithm for the MST. It starts with an empty MST and then at each step, it chooses some components. For each of them, it finds the edge with the minimum cost connecting this component to any other component and adds this edge to the minimum spanning tree. Let's apply this algorithm here. Assume that at step #$x$, the components are of the form of intervals of length $2^{x}$ i.e component #$i$ has nodes in $[i * 2^{x};(i + 1) * 2^{x} - 1]$. Let's see what the algorithm does. Let's see what happens for components where $i$ is odd. Assume the minimum cost for connecting this component is $c$. You can see that $c$ can't be less than $2^{x}$. That's because this intervals contains integers that have all the possible combinations of the first $x$ bits. Take $x = 2$ and $i = 1$, for example: the numbers are (in binary) $100$, $101$, $110$, $111$. All the possible combinations for the first $x$ bits are there! Notice that if you choose $c < 2^{x}$, you're changing the first $x$ bits. We have all possible combinations of them in the component so we'll make a cycle. That makes the minimum cost $2^{x}$. There's always a way to make a connection with cost $2^{x}$ which is connecting the first node of this component with the first node of the previous component (i.e connect node $i * 2^{x}$ with node $(i - 1) * 2^{x}$). Notice that $i*2^{x}\oplus(i-1)*2^{x}=2^{x}$ because $i$ is odd (Can you see why this is false for even $i$?). After that happens, the 2 components will form one big component and the components will be in the form of intervals of length $2^{x + 1}$ and the algorithm will repeat the same pattern!! Notice that at the beginning, the nodes are of the form of intervals with length 1 so the algorithm will work like that until the MST is constructed. Each node is the first node of its component and its component will have an odd index exactly once because after that it'll be in the middle of another big component. When that happens, it'll be when $2^{x} = lsb(x)$. Therefore, node $u$ adds $lsb(u)$ to the answer! Now let's see how to calculate that quickly. Let $f(x)$ be the number of integers $y$ such that $1 \le y \le n$ and $lsb(y) = x$, then $\sum_{i=1}^{n}l s b(i)=\sum_{i=1}^{n}f(i)*i$. $f(i) > 0$ if and only if $i$ is a power of 2 so this sum is equivalent to $\sum_{i=1}^{[l o g(n)]}f(2^{i})*2^{i}$. Basically, the first number $y$ such that $lsb(y) = x$ is $x$ and then the period is $2 * x$. Take 4 to see that. The integers $y$ such that $lsb(y) = 4$ are ${4, 12, 20, 28, etc.}$ Therefore, $f(x)=\lfloor{\frac{n-x}{2\cdot x}}\rfloor+1$ for $1 \le x \le n$ and x is a power of 2. Let's see how the sequence of $lsb(x)$ is constructed. We start with ${1}$ and at the $i^{th}$ step, we copy the sequence and concatenate it to itself and add $2^{i}$ in the middle. $\{1\}\implies\{1,2,1\}\implies\{1,2,1,4,1,2,1\}\implies\{1,2,1,4,1,2,1,8,1,2,1,4,1,2,1\}$ Let $f(x)=\sum_{i=1}^{x}l s b(i)$. Let $dp[i] = f(2^{i} - 1)$. You can see from the pattern above that $dp[i] = 2 * dp[i - 1] + 2^{i - 1}$ for $1 < i$ (with the base case that $dp[1] = 1$). Let's find a recurrence for $f(x)$. Denote $msb(x)$ as the value of the most significant bit set to 1. The sum can be split into 2 parts : the sum from 1 to $msb(x)$ and the sum from $msb(x) + 1$ to $x$. You can see that in the second sum, $lsb(i)$ can never be equal to $msb(x)$, so we can remove that bit safely without affecting the answer. Removing that bit is like xoring with $msb(x)$ which makes the sum start at 1 and end at $x\oplus m s b(x)$ which is $f(x\oplus m s b(x))$. Therefore, $f(x)=f(m s b(x))+f(x\oplus m s b(x))$. The first part can be calculated with the help of our $dp$ because $msb(x)$ is a power of 2 and the second part goes recursively. Basically, for each $i$ such that the $i^{th}$ bit is set to 1, we add $dp[i] + 2^{i}$ to the answer. Time complexity : $O(log(n))$.
[ "bitmasks", "dp", "graphs", "implementation", "math" ]
1,900
"#include <iostream>\nusing namespace std;\nlong long dp[50];\nint main()\n{\n\tlong long n;\n\tscanf(\"%I64d\",&n);\n\tfor (int i=1;i<50;i++)\n\tdp[i]=2LL*dp[i-1]+(1LL<<(i-1));\n\tn--;\n\tlong long ans=0;\n\tfor (int i=0;i<50;i++)\n\t{\n\t\tif (n&(1LL<<i))\n\t\tans+=dp[i]+(1LL<<i);\n\t}\n\tprintf(\"%I64d\",ans);\n}"
959
F
Mahmoud and Ehab and yet another xor task
Ehab has an array $a$ of $n$ integers. He likes the bitwise-xor operation and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud $q$ queries. In each of them, he gave Mahmoud 2 integers $l$ and $x$, and asked him to find the number of subsequences of the first $l$ elements of the array such that their bitwise-xor sum is $x$. Can you help Mahmoud answer the queries? A subsequence can contain elements that are not neighboring.
Let's solve a simpler version of the problem. Assume the queries only ask you to see whether the answer is 0 or positive instead of the exact answer. We can answer all the queries offline. We can keep a set containing all the possible xors of subsequences and update it for each prefix. Initially, the set contains only 0 (the xor of the empty subsequence). For each index $i$ in the array, we can update the set by adding $x\oplus a_{i}$ to the set for all $x$ in the set. The intuition behind it is that there's a subsequence with xor equal to $x$ (as $x$ is in the set) and if we add $a_{i}$ to it, its xor will be $x\oplus a_{i}$, so we should add it to the set. That's a slow solution to update the set, but we have some observations:- If $x$ is in the set and $y$ is in the set, $x\oplus y$ must be in the set. To see that, let $x$ be the xor of some elements and $y$ be the xor of other elements. $x\oplus y$ must be the xor of the non-common elements (because the common elements will annihilate) so it must be in the set. If $x$ is in the set and $y$ isn't in the set, $x\oplus y$ can't be in the set. This could be proved by contradiction. Assume $x\oplus y$ is in the set, then, by the first observation, $(x\oplus y)\oplus x$ must be in the set. This is equivalent to $y$ which we said that it isn't in the set. Therefore, $x\oplus y$ isn't in the set. Basically, if $a_{i}$ is already in the set, we do nothing because updating the set would do nothing but extra operations according to the first observation, and if $a_{i}$ isn't in the set, we don't even waste a single operation without extending the set! That makes the total complexity $O(n + maxAi)$ or $O((n + maxAi)log(maxAi))$ depending on implementation because each element is added to the set exactly once. To solve our problem, let's see the naiive dynamic programming solution. Let $dp[i][x]$ be the number of subsequences of the first $i$ elements with xor $x$. $d p[i][x]=d p[i-1][x]+d p[i-1][x\oplus a_{i}]$. The intuition behind it is exactly the same as the intuition behind the set construction. Let's prove that $dp[i][x]$ is equal for all $x$ belonging to the set! Let's assume this holds true for $i - 1$ and see what happens in the transition to $i$. Notice that it holds true for $i = 0$. Let $j$ be the value that $dp[i - 1][x]$ is equal to for all $x$ belonging to the set. If $a_{i}$ is in the set, and $x$ is in the set, $x\oplus a_{i}$ is in the set (observation #1). Therefore, $dp[i - 1][x] = j$ and $d p[i-1][x\oplus a_{i}]=j$ which makes $dp[i][x] = 2 * j$ for all $x$ in the set. Notice that the set doesn't change so $dp[i][x] = 0$ for all $x$ that aren't in the set. If $a_{i}$ isn't in the set, we have 3 cases for $x$. If $x$ is in the set, $x\oplus a_{i}$ isn't in the set. Therefore, $dp[i][x] = j + 0 = j$. If $x$ is to be added to the set in this step, $x\oplus a_{i}$ is in the set. Therefore, $dp[i][x] = 0 + j = j$. Otherwise, $dp[i][x] = 0$. To summarize, we'll maintain the set. For each integer, if it's in the set, we'll just multiply $j$ by 2. Otherwise, we'll update the set. We'll then answer all the queries for that prefix (saying 0 or $j$) depending on whether $x$ is in the set. Time complexity : $O(n + maxAi)$ if you implement the "set" with a vector and an array.
[ "bitmasks", "dp", "math", "matrices" ]
2,400
"#include <iostream>\n#include <vector>\nusing namespace std;\n#define mod 1000000007\nvector<pair<int,int> > v[100005];\nint arr[100005],a[100005];\nvector<int> s;\nbool b[(1<<20)];\nint main()\n{\n\tint n,q;\n\tscanf(\"%d%d\",&n,&q);\n\tfor (int i=0;i<n;i++)\n\tscanf(\"%d\",&arr[i]);\n\tfor (int i=0;i<q;i++)\n\t{\n\t\tint l,x;\n\t\tscanf(\"%d%d\",&l,&x);\n\t\tv[l-1].push_back({x,i});\n\t}\n\ts.push_back(0);\n\tb[0]=1;\n\tint ans=1;\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tif (b[arr[i]])\n\t\tans=(ans*2)%mod;\n\t\telse\n\t\t{\n\t\t\tint tmp=s.size();\n\t\t\tfor (int x=0;x<tmp;x++)\n\t\t\t{\n\t\t\t\ts.push_back(s[x]^arr[i]);\n\t\t\t\tb[s.back()]=1;\n\t\t\t}\n\t\t}\n\t\tfor (int x=0;x<v[i].size();x++)\n\t\ta[v[i][x].second]=ans*b[v[i][x].first];\n\t}\n\tfor (int i=0;i<q;i++)\n\tprintf(\"%d\\n\",a[i]);\n}"
960
A
Check the string
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, \textbf{at least one 'a' and one 'b'} exist in the string. B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time. You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
Traverse the string once and check if the ASCII value of all characters is greater than or equal or the ASCII value of the previous character. This ensures that the string does not have a,b,c in wrong order. Also, while traversing the string, keep three separate counters for the number of 'a', 'b' and 'c' along. Now, do a simple check on the condition for the count of 'c'. The hack case for many solutions was to check that the count of 'a' is atleast 1 and the count of 'b' is atleast 1.
[ "implementation" ]
1,200
#include<bits/stdc++.h> #define rep(i,start,lim) for(lld i=start;i<lim;i++) #define repd(i,start,lim) for(lld i=start;i>=lim;i--) #define scan(x) scanf("%lld",&x) #define print(x) printf("%lld ",x) #define f first #define s second #define pb push_back #define mp make_pair #define br printf("\n") #define sz(a) lld((a).size()) #define YES printf("YES\n") #define NO printf("NO\n") #define all(c) (c).begin(),(c).end() #define INF 1011111111 #define LLINF 1000111000111000111LL #define EPS (double)1e-10 #define MOD 1000000007 #define PI 3.14159265358979323 using namespace std; typedef long double ldb; typedef long long lld; lld powm(lld base,lld exp,lld mod=MOD) {lld ans=1;while(exp){if(exp&1) ans=(ans*base)%mod;exp>>=1,base=(base*base)%mod;}return ans;} lld ctl(char x,char an='a') {return (lld)(x-an);} char ltc(lld x,char an='a') {return (char)(x+an);} #define bit(x,j) ((x>>j)&1) typedef vector<lld> vlld; typedef pair<lld,lld> plld; typedef map<lld,lld> mlld; typedef set<lld> slld; #define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define mxm(a,b) a = max(a,b) #define mnm(a,b) a = min(a,b) #define endl '\n' #define fre freopen("1.in","r",stdin); freopen("1.out","w",stdout); #define N 1000005 int main() { //sync; string s; map<char,lld> m; cin>>s; lld k = sz(s); string tmp = ""; tmp += s[0]; rep(i,1,k) if(s[i]!=s[i-1]) tmp+=s[i]; rep(i,0,k) m[s[i]]++; if(tmp != "abc") return 0*NO; if(m['c']!=m['a'] and m['c']!=m['b']) return 0*NO; if(m['a']>=1 and m['b']>=1) return 0*YES; else return 0*NO; return 0; }
960
B
Minimize the error
You are given two arrays $A$ and $B$, each of size $n$. The error, $E$, between these two arrays is defined $E=\sum_{i=1}^{n}(a_{i}-b_{i})^{2}$. You have to perform \textbf{exactly} $k_{1}$ operations on array $A$ and \textbf{exactly} $k_{2}$ operations on array $B$. In one operation, you have to choose one element of the array and increase or decrease it by $1$. Output the minimum possible value of error after $k_{1}$ operations on array $A$ and $k_{2}$ operations on array $B$ have been performed.
The problem can be interpreted as follows: array $B$ is fixed and a total of $k_{1} + k_{2} = K$ operations allowed on $A$. Let the array $C$ be defined as $Ci = |Ai - Bi|$ Now this is just a simple greedy problem where value of $E=\sum_{i=1}^{n}C_{i}^{2}$ is to be minimized after exactly $K$ subtraction/addition operations spread over the elements of array $C$. Till $E$ is non-zero, the largest element is chosen and $1$ is subtracted from it. This is done as currently we want to maximize the reduction in error per operation and decreasing an element $x$ by $1$ reduces error by $x^{2} - (x - 1)^{2} = 2 \cdot x - 1$. Once all the elements become zero, we can use the remaining moves to alternately increase and decrease the same element till we run out of moves. This can be implemented using a priority queue or by sorting the array $C$ and iterating over it. Expected complexity: $O(N \cdot K \cdot log(N))$ or $O(N \cdot log(N))$
[ "data structures", "greedy", "sortings" ]
1,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; priority_queue<ll> pq; int main(){ int n, k1, k2, k; cin>>n>>k1>>k2; k = k1+k2; vector<ll> a(n), b(n), arr(n); for(int i=0 ; i<n ; ++i) cin>>a[i]; for(int i=0 ; i<n ; ++i){ cin>>b[i]; arr[i] = abs(a[i]-b[i]); pq.push(arr[i]); } while(k>0){ ll curr = pq.top(); pq.pop(); pq.push(abs(curr-1)); k--; } ll ans = 0; while(!pq.empty()){ ll curr = pq.top(); ans += (curr*curr); pq.pop(); } cout<<ans; }
960
C
Subsequence Counting
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size $n$ has $2^{n} - 1$ non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence $ - $ Minimum_element_of_subsequence $ ≥ d$ Pikachu was finally left with $X$ subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers $X$ and $d$. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than $10^{18}$. Note the number of elements in the output array should not be more than $10^{4}$. If no answer is possible, print $ - 1$.
Let's call a subsequence valid if the difference of maximum element and minimum element is less than d. For an array of size $n$ with all the elements equal, there are $2^{n} - 1$ non-empty subsequences and all of them are valid. This is because for any subsequence, the difference of maximum element and minimum element is always zero. We will use this observation in constructing the answer. Let's look at the binary representation of $X$. If the $i^{th}$ bit is set in X, we will add $i$ equal elements (let's say $y$) in our final array. However this would give us $2^{i} - 1$ non-empty valid subsequences. To correct this, we will add a separate element $y + d$ in the final array so that the final contribution of $i^{th}$ bit becomes $2^{i}$. We will carry out the same process for all the bits, keeping a counter of the previous In this way, the length of the final array will never exceed 600 elements. Expected Complexity : O(logX * logX)
[ "bitmasks", "constructive algorithms", "greedy", "implementation" ]
1,700
#include<bits/stdc++.h> #define rep(i,start,lim) for(lld i=start;i<lim;i++) #define repd(i,start,lim) for(lld i=start;i>=lim;i--) #define scan(x) scanf("%lld",&x) #define print(x) printf("%lld ",x) #define f first #define s second #define pb push_back #define mp make_pair #define br printf("\n") #define sz(a) lld((a).size()) #define YES printf("YES\n") #define NO printf("NO\n") #define all(c) (c).begin(),(c).end() #define INF 1011111111 #define LLINF 1000111000111000111LL #define EPS (double)1e-10 #define MOD 1000000007 #define PI 3.14159265358979323 using namespace std; typedef long double ldb; typedef long long lld; lld powm(lld base,lld exp,lld mod=MOD) {lld ans=1;while(exp){if(exp&1) ans=(ans*base)%mod;exp>>=1,base=(base*base)%mod;}return ans;} lld ctl(char x,char an='a') {return (lld)(x-an);} char ltc(lld x,char an='a') {return (char)(x+an);} #define bit(x,j) ((x>>j)&1) typedef vector<lld> vlld; typedef pair<lld,lld> plld; typedef map<lld,lld> mlld; typedef set<lld> slld; #define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define mxm(a,b) a = max(a,b) #define mnm(a,b) a = min(a,b) #define endl '\n' #define fre freopen("1.in","r",stdin); freopen("1.out","w",stdout); #define N 1000005 int main() { //sync; lld x,d; vector<lld> ans; cin>>x>>d; lld num = 1, cnt = 0; repd(i,60,1) if(bit(x,i)) { rep(j,0,i) ans.pb(num); cnt++; num+=(d+1); } while(cnt--) ans.pb(num),num+=(d+1); if(x%2) ans.pb(num); cout<<sz(ans)<<endl; for(auto i:ans) cout<<i<<" "; return 0; }
960
D
Full Binary Tree Queries
You have a full binary tree having infinite levels. Each node has an initial value. If a node has value $x$, then its left child has value $2·x$ and its right child has value $2·x + 1$. The value of the root is $1$. You need to answer $Q$ queries. There are $3$ types of queries: - Cyclically shift the \textbf{values} of all nodes on the same level as node with value $X$ by $K$ units. (The values/nodes of any other level are not affected). - Cyclically shift the \textbf{nodes} on the same level as node with value $X$ by $K$ units. (The subtrees of these nodes will move along with them). - Print the value of every node encountered on the simple path from the node with value $X$ to the root. Positive $K$ implies right cyclic shift and negative $K$ implies left cyclic shift. It is guaranteed that atleast one type $3$ query is present.
Let us define the root of the tree to be at level $L = 1$. Now, the level $L$ for any value $X$ can be found using this formula: $L = 64 -$ (Number of leading unset bits in $X$). In C++, you can conveniently calculate the leading unset bits by using __builtin_clzll($X$). Let us imagine each level of the tree as an array $A_{L}$. Observe that we only need to consider $L$ upto $60$ due to the constraint that $X \le 10^{18}$. Queries of type $1$ are equivalent to performing a cyclic shift of $K$ on array $A_{L}$. Queries of type $2$ are equivalent to performing a cyclic shift of $K$ on array $A_{L}$ , $2 \cdot K$ on array $A_{L + 1}$ , $2^{2} \cdot K$ on array $A_{L + 2}$ ... $2^{Z} \cdot K$ on array $A_{L + Z}$ and so on. Since we only care about the first $60$ levels, $0 \le Z \le 60 - L$. Now,we can store the net shift $S_{L}$ of each level. Note that, for level $L$, we calculate $S_{L}$ under modulo $2^{L - 1}$ because there are exactly $2^{L - 1}$ values in some $A_{L}$. Finally, to answer queries of type $3$, do the following: Let the original index(0-indexed) of $X$ in $A_{L}$ be $P$ ($P = X - 2^{L - 1}$). The new index after the shift will be $\bar{\boldsymbol{P}}$ $((P+S_{L})\;\mathrm{mod}\;2^{L-1}+2^{L-1})\;\mathrm{mod}\;2^{L-1}$. The original value at this index was $V=2^{L-1}+{\bar{P}}$. We can find the parent of this value in the original tree by dividing $V$ by $2$ (Integer Division).Thus, We can now find all the values in the path from $V$ to the root in the original tree. To get the values in the current tree, we just apply the opposite shift at each level to find the value and print it. Let the original value at index $P$ in $A_{L}$ at some level $L$ be $V$. The current value at this position after the shift will be the same as the value at index $\bar{\boldsymbol{P}}$ $((P+S_{L}\cdot-1)\mathrm{~mod~}2^{L-1}+2^{L-1})\mathrm{~mod~}2^{L-1}$ in the original array. Let this value be $Z$. Now,$Z=2^{L-1}+\bar{P}$. Print $Z$ and set $V = V / 2$. Repeat Step $2$ and stop when $V = 0$. Complexities of: Query $1$: $O(1)$. Query $2$: $O(60)$. Query $3$: $O(60)$. Overall: $O(60 \cdot Q)$ Refer to the code for further understanding.
[ "brute force", "implementation", "trees" ]
2,100
//Gvs Akhil (Vicennial) #include<bits/stdc++.h> #define int long long #define pb push_back #define eb emplace_back #define mp make_pair #define mt make_tuple #define ld(a) while(a--) #define tci(v,i) for(auto i=v.begin();i!=v.end();i++) #define tcf(v,i) for(auto i : v) #define all(v) v.begin(),v.end() #define rep(i,start,lim) for(long long (i)=(start);i<(lim);i++) #define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define osit ostream_iterator #define INF 0x3f3f3f3f #define LLINF 1000111000111000111LL #define PI 3.14159265358979323 #define endl '\n' #define trace1(x) cerr<<#x<<": "<<x<<endl #define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl #define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl #define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl #define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl #define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl const int N=1000006; using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef long long ll; typedef vector<long long> vll; typedef vector<vll> vvll; typedef long double ld; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<vii> vvii; typedef tuple<int,int,int> iii; typedef set<int> si; typedef complex<double> pnt; typedef vector<pnt> vpnt; typedef priority_queue<ii,vii,greater<ii> > spq; const ll MOD=1000000007LL; template<typename T> T gcd(T a,T b){if(a==0) return b; return gcd(b%a,a);} template<typename T> T power(T x,T y,ll m=MOD){T ans=1;while(y>0){if(y&1LL) ans=(ans*x)%m;y>>=1LL;x=(x*x)%m;}return ans%m;} int shift[66]; inline int getlev(int x){ int z=__builtin_clzll(x); return 64-z; } inline int getmod(int x){ return (1LL<<(x-1)); } void addshift(int x,int k){ int m=getmod(x); if(k>=m) k%=m; shift[x]+=k; if(shift[x]>=m) shift[x]-=m; if(shift[x]<0) shift[x]+=m; } int getorig(int V,int l){ int fval=(1LL<<(l-1)); // 2^(L-1) int mod=getmod(l); int P= V-fval; int Z= fval+((P-shift[l])%mod + mod)%mod; return Z; } int32_t main(){ sync; int q; cin>>q; while(q--){ int t,x,k; cin>>t>>x; int l=getlev(x); if(t==1){ cin>>k; k%=getmod(l); addshift(l,k); } else if(t==2){// propogating cin>>k; k%=getmod(l); if(k<0) k+=getmod(l); int curr=1; for(int i=l;i<=60;i++){ addshift(i,k*curr); curr<<=1; } } else{ // printing int P= x - (1LL<<(l-1)); // Finding index in array int V= (1LL<<(l-1)) + ((P+shift[l])%(1LL<<(l-1)) + (1LL<<(l-1)) )%(1ll<<(l-1)); //Finding original value at the new index of X after performing the shift. for(int i=l;i>=1;i--){ int Z = getorig(V,i); // Finding the current value cout<<Z<<" "; // printing the current value V>>=1; // dividing the original value by 2 to get its parent value } cout<<endl; } } }
960
E
Alternating Tree
Given a tree with $n$ nodes numbered from $1$ to $n$. Each node $i$ has an associated value $V_i$. If the simple path from $u_1$ to $u_m$ consists of $m$ nodes namely $u_1 \rightarrow u_2 \rightarrow u_3 \rightarrow \dots u_{m-1} \rightarrow u_{m}$, then its alternating function $A(u_{1},u_{m})$ is defined as $A(u_{1},u_{m}) = \sum\limits_{i=1}^{m} (-1)^{i+1} \cdot V_{u_{i}}$. A path can also have $0$ edges, i.e. $u_{1}=u_{m}$. Compute the sum of alternating functions of all unique simple paths. Note that the paths are directed: two paths are considered different if the starting vertices differ or the ending vertices differ. The answer may be large so compute it modulo $10^{9}+7$.
An important observation for the question is $A(u,v) = -A(v,u)$ if there are even number of nodes on the simple path from $u$ to $v$ $A(u,v) = A(v,u)$ if there are odd number of nodes on the simple path from $u$ to $v$ Hence $A(u,v) + A(v,u)=0$ for paths with even number of nodes. Hence the task has been reduced to finding the total sum of alternating function of paths with odd number of nodes. Also we can make use of the fact that $A(u,v) + A(v,u) = 2*A(u,v)$ , but this does not hold true when $u=v$, hence we must handle this case by subtracting $\sum\limits_{i=1}^{n} V_{i}$ from the final answer. Now with the help of a single dfs we can calculate $odd_i$ the number of paths in the subtree of $i$ with odd number of nodes ending at node $i$. $even_i$ the number of paths in the subtree of $i$ with even number of nodes ending at node $i$. In the first part of the solution, for each node $i$, we calculate its contribution to the alternating function for paths passing through this node but strictly lying within its subtree. For doing this we can merge two paths with either both having even or both having odd number of nodes ending at its children to create odd length paths. For the case where both the paths have even number of nodes, the current node's contribution to the summation is $V_i$ because its position in the sequence of nodes is odd . Similarly, we add $-V_i$ for the other case. This can be done using a single dfs in $O(n)$ time as we have $odd_i$ and $even_i$ for all the nodes. Now for the second part of the question, we have to consider the paths which end up outside the subtree. We have the information $odd_i$ and $even_i$ . We have to merge these paths with those ending at $parent_i$. How do we get this information? Note that $odd_i$ and $even_i$ just represent paths strictly lying within the subtree of $i$ but not the entire tree. An important observation for this computation is - If node $u$ has a total of $x$ odd and $y$ even length paths ending at it then, if $v$ is the neighbour of $u$ then $v$ has a total of $y$ odd and $x$ even length paths ending at it. It is fairly simple to observe. We know $odd_{root}$ and $even_{root}$ and since the subtree of $root$ is the entire tree, we can use these values for our requirement. Now let's represent the total number of odd and even length paths ending at $i$ by $todd_i$ and $teven_i$ respectively. From our previous observation, if $i$ is odd number of nodes away from the $root$ node - $todd_i = even_{root}$ $teven_i = odd_{root}$ if $i$ is even number of nodes away from the $root$ node - $todd_i = odd_{root}$ $teven_i = even_{root}$ The number of paths ending at $parent_i$ but lying strictly outside the subtree of $i$ can be calculated - odd length paths $= todd_{parent_i}-even_i$ even length paths $= teven_{parent_i}-odd_i$ Now we have to construct odd-length paths by merging paths in the subtree of $i$ ending at node $i$ with paths ending at $parent_i$ but strictly lying outside the subtree of $i$. For paths with odd-length component ending at $i$ we must add $V_i$ to the summation and $-V_i$ otherwise. Finally, the summation of contributions of each node yields you the total summation of alternating functions for all pair of nodes. This can be done for each node in $O(n)$ time. The overall time complexity of the solution is $O(n)$.
[ "combinatorics", "dfs and similar", "divide and conquer", "dp", "probabilities", "trees" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int M=1000005,mod=1e9+7; vector<int> adj[M]; int par[M],lev[M]; ll v[M]; ll e[M],o[M]; ll ans,res,n; ll powmod(ll base, ll exponent) { //cout<<base<<" "<<exponent<<endl; ll ans=1; while(exponent) { while(exponent%2==0) { base=(base*base)%mod; exponent/=2; } exponent--; ans=(ans*base)%mod; } return ans; } void dfs(int x,int depth) { //o[x]++; lev[x]=depth; int cno=0; for(int i=0;i<adj[x].size();i++) { int c=adj[x][i]; if(c!=par[x]) { par[c]=x; dfs(c,depth+1); if(cno>0) { ans=( (ans+ 2*( o[x]*e[c]%mod - e[x]*o[c]%mod + mod)%mod*v[x]%mod)+mod )%mod; } cno++; o[x]+=e[c]; e[x]+=o[c]; } } o[x]++; } int main() { //freopen("o.out","r",stdin); cin>>n; for(int i=1;i<=n;i++) { cin>>v[i]; } for(int i=1;i<n;i++) { int u,v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } dfs(1,0); //cout<<ans<<endl; for(int i=1;i<=n;i++) { //cout<<"###"<<i<<endl; if(lev[i]%2) { ans=((ans+2*(o[i]*(e[1]-o[i]+1)%mod - e[i]*(o[1]-e[i])%mod +mod)%mod*v[i]%mod)%mod+mod )%mod; } else { ans=((ans+2*(o[i]*(o[1]-o[i]+1)%mod - e[i]*(e[1]-e[i])%mod +mod)%mod*v[i]%mod)%mod+mod )%mod; } //cout<<ans<<endl; ans=((ans-v[i])%mod+mod)%mod; // cout<<i<<" "<<ans<<endl; //cout<<ans<<endl; } cout<<ans<<endl; }
960
F
Pathwalks
You are given a directed graph with $n$ nodes and $m$ edges, with all edges having a certain weight. There might be multiple edges and self loops, and the graph can also be disconnected. You need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges are in strictly increasing order, and these edges come in the order of input. Among all such paths, you need to find the the path that has the maximum possible number of edges, and report this value. Please note that the edges picked don't have to be consecutive in the input.
The problem is similar to Longest Increasing Subsequence, done on a graph instead of an array. The solution for this problem can be obtained in the following ways:- $Approach1$ Maintain a map for every node, consisting of weights and the corresponding max no of edges you can achieve for some path ending at that node at a given point. Now when you process the next edge, suppose $a_{i}$ $b_{i}$ $w_{i}$ , you query max no of edges having weight $< w_{i}$ in map of node $a_{i}$ . Let's call this $X$. Now, you try to insert $X + 1$ for weight $w_{i}$ in map of node $b_{i}$. Maintain it in such a way that no of edges for higher weights in a particular node is always larger than that for smaller weights. You can do this with (kind of) the conventional sliding window idea, by removing higher weight edges with smaller values than the current inserted answer in the map, or not inserting the current value at all because an equivalent or better answer exists for weights $ \le w_{i}$ for the node $b_{i}$. Finally the max of all such $X + 1$ you encounter during processing the graph is the maximum number of edges in any given path. $Approach2$ You can also solve this problem with the help of sparse/dynamic/persistent segment tree on every node of the graph. Suppose you are at the $i^{th}$ edge at some point in your processing, and the query was $a_{i}$ $b_{i}$ $w_{i}$. Do a Range Max Query on segtree at node $a_{i}$, uptil value $w_{i - 1}$. Suppose this answer was $X$. Now update segtree at location $b_{i}$ with value of $(X + 1)$. Store the max of all such $(X + 1)$, and this is the length of longest path in your graph.
[ "data structures", "dp", "graphs" ]
2,100
#include <bits/stdc++.h> using namespace std; vector<map<int,int> > s; int getedgelen(int a, int w) { auto it = s[a].lower_bound(w); if(it == s[a].begin()) return 1; it--; return (it->second)+1; } int32_t main() { ios::sync_with_stdio(false);cin.tie(0); int n,m,a,b,w; cin>>n>>m; s.resize(n+1); int ans = 0; while(m--) { cin>>a>>b>>w; int val = getedgelen(a,w); if(getedgelen(b,w+1) > val) continue; s[b][w] = max(s[b][w],val); auto it = s[b].upper_bound(w); while(!(it==s[b].end() || it->second > val)) { it = s[b].erase(it); } ans = max(ans,val); } cout<<ans; return 0; }
960
G
Bandit Blues
Japate, while traveling through the forest of Mala, saw $N$ bags of gold lying in a row. Each bag has some \textbf{distinct} weight of gold between $1$ to $N$. Japate can carry only one bag of gold with him, so he uses the following strategy to choose a bag. Initially, he starts with an empty bag (zero weight). He considers the bags in some order. If the current bag has a higher weight than the bag in his hand, he picks the current bag. Japate put the bags in some order. Japate realizes that he will pick $A$ bags, if he starts picking bags from the front, and will pick $B$ bags, if he starts picking bags from the back. By picking we mean replacing the bag in his hand with the current one. Now he wonders how many permutations of bags are possible, in which he picks $A$ bags from the front and $B$ bags from back using the above strategy. Since the answer can be very large, output it modulo $998244353$.
The problem can be seen as to count the number of permutations such that the number of records from the front is A and the number of records from the back is B, where a record is an element greater than all previous. let $s(A, N)$ be the number of permutations such that for $N$ elements exactly $A$ records are present from front. Then $s(A, N)$ can be calculated as $s(A, N) = s(A - 1, N - 1) + (N - 1) * s(A, N - 1)$ Let's consider the smallest element if we have it as a record then we can place it on front and have the remaining $A - 1$ records in $s(A - 1, N - 1)$ ways or we don't have it as a record than we can have the remaining $A$ records in $s(A, N - 1)$ ways and place this smallest element at any of the remaining $N - 1$ positions. let $h(A, B, N)$ be the number of permutations such that the number of records from the front is $A$ and the number of records from the back is $B$. $h(A,B,N)=\sum_{k=0}^{N-1}s(k,A-1)*s(N-k-1,B-1)*{\binom{N-1}{k}}$ $k$ elements are chosen and placed before the largest record such that exactly $A - 1$ records are present in them in $s(k, A - 1)$ ways and the remaining $N - k - 1$ after the largest record such that $B - 1$ records are present in $s(N - k - 1, B - 1)$ ways.We choose the $k$ elements in $\textstyle{\binom{N-1}{k}}$ ways. Now we claim that $h(A,B,N)=s(A+B-2,N-1)*{\binom{A+B-2}{A-1}}$ Proof - Consider permutations of length $N - 1$ with $A + B - 2$ records of which $A - 1$ are colored blue and $B - 1$ are colored green. Note - Coloring a record means coloring the record and every element between this record and previous record. We can choose permutations of $N - 1$ with $A + B - 2$ records ,then choose $A - 1$ of these records to be blue in $s(A+B-2,N-1)*{\binom{A+B-2}{A-1}}$ ways. Also for any $k$ between $0$ and $N - 1$ we choose $k$ elements to be in blue then make permutations in these $k$ elements with $A - 1$ records and make permutations with exactly $B - 1$ records on remaining $N - k - 1$ elements, thus we have in total $\sum_{k=\mathbb{N}}^{N-1}s(k,A-1)*s(N-k-1,B-1)*{\binom{N-1}{k}}$ ways. Hence both are equivalent. Therefore calculating $s(A + B - 2, N - 1)$ gives our answer. $s(k, n)$ forms stirling number of first kind which can be calculated by coefficent of $x^{k}$ in $x * (x + 1) * (x + 2) * ..... * (x + n - 1)$ using FFT.
[ "combinatorics", "dp", "fft", "math" ]
2,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define pb push_back const int mod = 998244353; const int root = 15311432; const int root_1 = 469870224; const int root_pw = 1 << 23; const int N = 400004; vector<int> v[N]; ll modInv(ll a, ll mod = mod){ ll x0 = 0, x1 = 1, r0 = mod, r1 = a; while(r1){ ll q = r0 / r1; x0 -= q * x1; swap(x0, x1); r0 -= q * r1; swap(r0, r1); } return x0 < 0 ? x0 + mod : x0; } void fft (vector<int> &a, bool inv) { int n = (int) a.size(); for (int i=1, j=0; i<n; ++i) { int bit = n >> 1; for (; j>=bit; bit>>=1) j -= bit; j += bit; if (i < j) swap (a[i], a[j]); } for (int len=2; len<=n; len<<=1) { int wlen = inv ? root_1 : root; for (int i=len; i<root_pw; i<<=1) wlen = int (wlen * 1ll * wlen % mod); for (int i=0; i<n; i+=len) { int w = 1; for (int j=0; j<len/2; ++j) { int u = a[i+j], v = int (a[i+j+len/2] * 1ll * w % mod); a[i+j] = u+v < mod ? u+v : u+v-mod; a[i+j+len/2] = u-v >= 0 ? u-v : u-v+mod; w = int (w * 1ll * wlen % mod); } } } if(inv) { int nrev = modInv(n, mod); for (int i=0; i<n; ++i) a[i] = int (a[i] * 1ll * nrev % mod); } } void pro(const vector<int> &a, const vector<int> &b, vector<int> &res) { vector<int> fa(a.begin(), a.end()), fb(b.begin(), b.end()); int n = 1; while (n < (int) max(a.size(), b.size())) n <<= 1; n <<= 1; fa.resize (n), fb.resize (n); fft(fa, false), fft (fb, false); for (int i = 0; i < n; ++i) fa[i] = 1LL * fa[i] * fb[i] % mod; fft (fa, true); res = fa; } int S(int n, int r) { int nn = 1; while(nn < n) nn <<= 1; for(int i = 0; i < n; ++i) { v[i].push_back(i); v[i].push_back(1); } for(int i = n; i < nn; ++i) { v[i].push_back(1); } for(int j = nn; j > 1; j >>= 1){ int hn = j >> 1; for(int i = 0; i < hn; ++i){ pro(v[i], v[i + hn], v[i]); } } return v[0][r]; } int fac[N], ifac[N], inv[N]; void prencr(){ fac[0] = ifac[0] = inv[1] = 1; for(int i = 2; i < N; ++i) inv[i] = mod - 1LL * (mod / i) * inv[mod % i] % mod; for(int i = 1; i < N; ++i){ fac[i] = 1LL * i * fac[i - 1] % mod; ifac[i] = 1LL * inv[i] * ifac[i - 1] % mod; } } int C(int n, int r){ return (r >= 0 && n >= r) ? (1LL * fac[n] * ifac[n - r] % mod * ifac[r] % mod) : 0; } int main(){ prencr(); int n, p, q; cin >> n >> p >> q; ll ans = C(p + q - 2, p - 1); ans *= S(n - 1, p + q - 2); ans %= mod; cout << ans; }
960
H
Santa's Gift
Santa has an infinite number of candies for each of $m$ flavours. You are given a rooted tree with $n$ vertices. The root of the tree is the vertex $1$. Each vertex contains exactly one candy. The $i$-th vertex has a candy of flavour $f_i$. Sometimes Santa fears that candies of flavour $k$ have melted. He chooses any vertex $x$ randomly and sends the subtree of $x$ to the Bakers for a replacement. In a replacement, all the candies with flavour $k$ are replaced with a new candy of the same flavour. The candies which are not of flavour $k$ are left unchanged. After the replacement, the tree is restored. The actual cost of replacing one candy of flavour $k$ is $c_k$ (given for each $k$). The Baker keeps the price fixed in order to make calculation simple. Every time when a subtree comes for a replacement, the Baker charges $C$, no matter which subtree it is and which flavour it is. Suppose that for a given flavour $k$ the probability that Santa chooses a vertex for replacement is same for all the vertices. You need to find out the expected value of error in calculating the cost of replacement of flavour $k$. The error in calculating the cost is defined as follows. $$ Error\ E(k) =\ (Actual Cost\ –\ Price\ charged\ by\ the\ Bakers) ^ 2.$$ Note that the actual cost is the cost of replacement of one candy of the flavour $k$ multiplied by the number of candies in the subtree. Also, sometimes Santa may wish to replace a candy at vertex $x$ with a candy of some flavour from his pocket. You need to handle two types of operations: - Change the flavour of the candy at vertex $x$ to $w$. - Calculate the expected value of error in calculating the cost of replacement for a given flavour $k$.
The actual cost of replacing all candies of flavour $k$ in the subtree of vertex $x$ is $h_k(x) \cdot c_k$. Here, $h_k(x)$ is the number of vertices (candy) in the subtree of $x$ with value (flavour) $k$ and $c_k$ is the cost of replacing each candy of flavour $k$. Error $E(v)$ is defined as $(h_k(x) \cdot c_k - C) ^ 2$ = $h_k(x)^2 \cdot c_k^2 + C^2 - 2 \cdot h_k(x) \cdot c_k \cdot C$. Expectation of error $E(v)$ can be written $Exp[E(v)]$ = $Exp[h_k(x)^2 \cdot c_k^2 + C^2 - 2 \cdot h_k(x) \cdot c_k \cdot C]$ = $c_k ^ 2 \cdot Exp[h_k(x)^2] + Exp[C^2] - 2 \cdot c_k \cdot C \cdot Exp[h_k(x)]$. $Exp[h_k(x)]$ can be expressed as $\frac{\sum_{x=1}^{n} h_k(x)}{n}$. The above sum can be managed by adding or by subtracting the depth of node (assuming root to be of depth 1). $Exp[{h_k(x)}^2]$ can be expressed as $\frac{\sum_{x=1}^{n} h_k(x)^2}{n}$. It can be observed that for every pair of vertices with value $k$ we need to add depth of LCA to the answer. Now we need to find the summation $\sum\nolimits_{f_i=k} \sum\nolimits_{f_j=k} Dist(i,j)$. To find sum we use centroid decomposition. We create a centroid tree from the given tree. Initially, no vertices have been inserted or updated. We update vertices one by one. While inserting a vertex with value $k$. We need to calculate its distance with all other vertices with the same value and add to the answer. To do so we maintain few things for a given vertex $x$ in the centroid tree. $p(x)$ - Parent of vertex $x$ in the centroid tree $h_k(x)$ - Number of vertices currently present in the subtree of $x$ with value $v$ $a_k(x)$ - $\sum\nolimits_{i \in subtree(x)} distance(x,i)$ $b_k(x)$ - $\sum\nolimits_{i \in subtree(x)} distance(p(x),i)$ The distance of any given vertex $x$ with value $k$ with other vertices of same value is given as $a_k(x) + d_k(x)$. Here, $d_k(x)$ is $\sum\nolimits_{i \in all\ ancestor\ of\ x} distance(i,x) \cdot (h_k(p(i) - h_k(i)) + a_k(p(i)) - b_k(i))$ For each vertex, we need to store for all values $k$ present in the subtree. We can use a map for this purpose. In worst case, $O(n \cdot log(n))$ memory will be used.
[ "data structures", "trees" ]
3,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define pb push_back const int N = 400004; int n; vector<int> e[N]; int sz[N], par[N], sp[30][N]; int V[N], L[N], CS[N]; bool mark[N]; struct tri { long long A, B; int C; }; map<int, tri> nmp[N]; long long D[N]; // Sum of Distances long long S[N]; // Sum of Depth int T[N]; // Count //======================================PRE-PROCESS========================================= void getLevel(int u, int p = -1){ sp[0][u] = p; for(auto x : e[u]) if(x != p) { L[x] = 1 + L[u]; getLevel(x, u); } } void prepAncestor(){ for(int i = 1; (1 << i) <= n; ++i) { for(int j = 1; j <= n; ++j) { sp[i][j] = sp[i - 1][sp[i - 1][j]]; } } } int dist(int u, int v){ if(L[u] < L[v]) swap(u, v); int lgn = 0; while((1 << lgn) < n) lgn++; int ans = 0; for(int i = lgn; i >= 0; --i){ if(L[u] - (1 << i) >= L[v]){ u = sp[i][u]; ans += (1 << i); } } if(u == v) return ans; for(int i = lgn; i >= 0; --i){ if(sp[i][u] != sp[i][v]){ ans += 1 << (i + 1); u = sp[i][u]; v = sp[i][v]; } } return ans + 2; } //=================================CENTROID DECOMPOSITION=================================== void getSize(int u, int p = -1) { sz[u] = 1; for(auto v : e[u]) if(v != p && !mark[v]) { getSize(v, u); sz[u] += sz[v]; } } int getCentroid(int u, int p, int lim) { for(auto v : e[u]) if(v != p && !mark[v] && sz[v] > lim) { return getCentroid(v, u, lim); } return u; } void decompose(int u, int p = -1) { getSize(u); int cen = getCentroid(u, -1, sz[u] / 2); par[cen] = p == -1 ? cen : p; mark[cen] = true; for(auto v : e[cen]) if(v != p && !mark[v]) { decompose(v, cen); } } //==========================================QUERY-HANDLER=============================================== void updAns(int u, int add) { int Z = V[u]; tri tY = nmp[u][Z]; ll ret = tY.A; int y = u, x = par[u]; while(y != x) { tri tX = nmp[x][Z]; ret += 1LL * (tX.C - tY.C) * dist(x, u) + (tX.A - tY.B); y = x; tY = tX; x = par[x]; } ret <<= 1; int mul = add ? 1 : -1; D[Z] += mul * ret; S[Z] += mul * L[u]; T[Z] += mul; } void updTree(int u, bool add) { int Z = V[u]; int mul = add ? 1 : -1; for(int x = u; ; x = par[x]) { tri &tX = nmp[x][Z]; tX.C += mul; if(!tX.C) { nmp[x].erase(Z); } else { tX.A += mul * dist(u, x); tX.B += mul * dist(u, par[x]); } if(x == par[x]) break; } } void upd(int u, bool add) { if(add) { updTree(u, add); updAns(u, add); } else { updAns(u, add); updTree(u, add); } } //=========================================MAIN============================================ int main(){ int m, q, ac; scanf("%d %d %d %d", &n, &m, &q, &ac); for(int i = 1; i <= n; ++i) { scanf("%d", &V[i]); } for(int i = 2; i <= n; ++i) { int v; scanf("%d", &v); e[v].pb(i); e[i].pb(v); } for(int i = 1; i <= m; ++i) { scanf("%d", &CS[i]); } L[1] = 1; getLevel(1); prepAncestor(); decompose(1); for(int i = 1; i <= n; ++i) { upd(i, true); } while(q--) { int t; scanf("%d", &t); if(t == 1) { int u, v; scanf("%d %d", &u, &v); upd(u, false); V[u] = v; upd(u, true); } else if(t == 2) { int v; scanf("%d", &v); long double ans = S[v] * T[v] - D[v] / 2; ans *= 1LL * CS[v] * CS[v]; ans += 1LL * n * ac * ac; long long anst = 2LL * CS[v] * ac * S[v]; ans -= anst; cout << fixed << setprecision(12) << ans / n << "\n"; } } }
961
A
Tetris
You are given a following process. There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.
The answer will be equal to $\min\limits_{i = 1}^{n} cnt_i$, where $cnt_i$ is the number of squares that will appear in the $i$-th column.
[ "implementation" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, m; cin >> n >> m; vector<int> cnt(n); for (int i = 0; i < m; ++i) { int col; cin >> col; ++cnt[col - 1]; } cout << *min_element(cnt.begin(), cnt.end()) << endl; return 0; }
961
B
Lecture Sleep
Your friend Mishka and you attend a calculus lecture. Lecture lasts $n$ minutes. Lecturer tells $a_{i}$ theorems during the $i$-th minute. Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array $t$ of Mishka's behavior. If Mishka is asleep during the $i$-th minute of the lecture then $t_{i}$ will be equal to $0$, otherwise it will be equal to $1$. When Mishka is awake he writes down all the theorems he is being told — $a_{i}$ during the $i$-th minute. Otherwise he writes nothing. You know some secret technique to keep Mishka awake for $k$ minutes straight. However you can use it \textbf{only once}. You can start using it at the beginning of any minute between $1$ and $n - k + 1$. If you use it on some minute $i$ then Mishka will be awake during minutes $j$ such that $j\in[i,i+k-1]$ and will write down all the theorems lecturer tells. You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique \textbf{only once} to wake him up.
Let's iterate over all $i$ from $1$ to $n$ and if $t_{i}$ is equal to $1$ then add $a_{i}$ to the some variable $res$ and replace $a_{i}$ with $0$. Then answer will be equal to $r e s+\operatorname*{m}_{i=k}^{n}a_{j}{}=\underline{{{i}}}^{i}-k+1}a_{j}$, where $\sum_{j=i-k+1}^{i}a_{j}$ can be easily calculated with prefix sums for each $i$.
[ "data structures", "dp", "implementation", "two pointers" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; scanf("%d %d", &n, &k); vector<int> a(n); vector<int> t(n); int overall = 0; for (int i = 0; i < n; ++i) scanf("%d", &a[i]); for (int i = 0; i < n; ++i) scanf("%d", &t[i]); vector<int> pr(n); for (int i = 0; i < n; ++i) { if (i) pr[i] += pr[i - 1]; if (t[i] == 0) pr[i] += a[i]; else overall += a[i]; } int add = 0; for (int i = k - 1; i < n; ++i) add = max(add, pr[i] - (i >= k ? pr[i - k] : 0)); printf("%d\n", overall + add); return 0; }
961
C
Chessboard
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into $4$ pieces, each of size $n$ by $n$, $n$ is \textbf{always odd}. And what's even worse, some squares were of wrong color. $j$-th square of the $i$-th row of $k$-th piece of the board has color $a_{k, i, j}$; $1$ being black and $0$ being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be $2n$ by $2n$. You are allowed to move pieces but \textbf{not allowed to rotate or flip them}.
Since $n$ is odd, exactly $2$ pieces of the board will have upper left corner colored black (and exactly $2$ - white). Let's check every option to choose two pieces of the board so their upper left corners will be painted white when we assemble the board, calculate the number of board cells that have to be recolored, and find the minimum of this value among all possible choices.
[ "bitmasks", "brute force", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; const int N = 109; int n; string a[4][N]; int main() { cin >> n; for(int k = 0; k < 4; ++k) for(int i = 0; i < n; ++i){ cin >> a[k][i]; for(int j = 0; j < n; ++j) a[k][i][j] -= '0'; } vector <int> v; for(int k = 0; k < 4; ++k){ int sum = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) if((i + j) % 2 != a[k][i][j]) ++sum; v.push_back(sum); } int res = int(1e9); vector <int> perm; for(int k = 0; k < 4; ++k) perm.push_back(k); do{ int sum = 0; for(int k = 0; k < 4; ++k){ int id = perm[k]; if(k & 1) sum += v[id]; else sum += n * n - v[id]; } res = min(res, sum); }while(next_permutation(perm.begin(), perm.end())); cout << res << endl; }
961
D
Pair Of Lines
You are given $n$ points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?
If the number of points is less than $3$, then the answer is obviously YES. Else let's fix first $3$ points. Check if there is a solution if $1$-st and $2$-nd points lie on the same line. Just erase all points which lie on this line and check the remaining points if they belong to one line. If we didn't find the answer, let's check points $1$ and $3$ in the same way. If its failed again then line which contains point $1$ can't contain points $2$ and $3$, so points $2$ and $3$ must lie on one line. If we didn't succeed again, then there is no way to do it, so the answer is NO. Checking that points $a$, $b$ and $c$ belong to the same line can be done by calculating 2d version of cross product $(b - a) \times (c - a)$. It equals to $0$ if vectors $(b - a)$ and $(c - a)$ are collinear.
[ "geometry" ]
2,000
#include <bits/stdc++.h> #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define all(a) (a).begin(), (a).end() #define sz(a) int(a.size()) #define mp make_pair #define x first #define y second using namespace std; typedef long long li; typedef pair<int, int> pt; inline pt operator -(const pt &a, const pt &b) { return {a.x - b.x, a.y - b.y}; } inline li cross(const pt &a, const pt &b) { return a.x * 1ll * b.y - a.y * 1ll * b.x; } const int N = 200 * 1000 + 555; int n; pt p[N]; inline bool read() { if(!(cin >> n)) return false; fore(i, 0, n) scanf("%d%d", &p[i].x, &p[i].y); return true; } bool used[N]; bool check() { int i1 = -1, i2 = -1; fore(i, 0, n) { if(used[i]) continue; if(i1 == -1) i1 = i; else if(i2 == -1) i2 = i; } if(i2 == -1) return true; fore(i, 0, n) { if(used[i]) continue; if(cross(p[i2] - p[i1], p[i] - p[i1]) != 0) return false; } return true; } bool check2(pt a, pt b) { memset(used, 0, sizeof used); fore(i, 0, n) if(cross(b - a, p[i] - a) == 0) used[i] = 1; return check(); } inline void solve() { if(n <= 2) { puts("YES"); return; } if(check2(p[0], p[1]) || check2(p[0], p[2]) || check2(p[1], p[2])) puts("YES"); else puts("NO"); } int main(){ if(read()) { solve(); } return 0; }
961
E
Tufurama
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method. TV series have $n$ seasons (numbered $1$ through $n$), the $i$-th season has $a_{i}$ episodes (numbered $1$ through $a_{i}$). Polycarp thinks that if for some pair of integers $x$ and $y$ ($x < y$) exist both season $x$ episode $y$ and season $y$ episode $x$ then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
At first, it doesn't matter if some season has more than $n$ episodes, so we can set $a_{i} = min(a_{i}, n)$. Let's maintain next invariant: when we proceed $i$-th season we will have only seasons containing the episodes with indices $ \ge i$. Then the number of pairs $(i, y)$ is just number of seasons with index $ \le a_{i}$. One of the ways to maintain this invariant is the following: for each number of episodes $a_{i}$ store a list with indices of seasons with exactly $a_{i}$ episodes. Then after proceeding of $i$-th season just erase all seasons with exactly $i$ episodes. Maintaining seasons and counting them can be done by BIT with zeros and ones. Finally, notice, that we counted each pair $(x < y)$ twice, and also counted the pairs $(x, x)$, so we must subtract the number of pairs $(x, x)$ (where $a_{x} \ge x$) and divide the result by two.
[ "data structures" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 9; int n; int a[N]; int f[N]; vector <int> v[N]; void upd(int pos, int d){ for(; pos < N; pos |= pos + 1) f[pos] += d; } int get(int pos){ int res = 0; for(; pos >= 0; pos = (pos & (pos + 1)) - 1) res += f[pos]; return res; } int main() { scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%d", a + i); --a[i]; } for(int i = 0; i < n; ++i){ if(a[i] < N) v[a[i]].push_back(i); upd(i, 1); } long long res = 0; for(int i = 0; i < n; ++i){ int to = min(N - 1, a[i]); res += get(to); for(auto x : v[i]) upd(x, -1); } for(int i = 0; i < n; ++i) if(i <= a[i]) --res; assert(res % 2 == 0); cout << res / 2 << endl; }
961
F
k-substrings
You are given a string $s$ consisting of $n$ lowercase Latin letters. Let's denote $k$-substring of $s$ as a string $subs_{k} = s_{k}s_{k + 1}..s_{n + 1 - k}$. Obviously, $subs_{1} = s$, and there are exactly $\textstyle{\left[\!\!{\frac{n}{2}}\right]}$ such substrings. Let's call some string $t$ an \textbf{odd proper suprefix} of a string $T$ iff the following conditions are met: - $|T| > |t|$; - $|t|$ is an odd number; - $t$ is simultaneously a prefix and a suffix of $T$. For evey $k$-substring ($k\in[1,[{\frac{n}{2}}]]$) of $s$ you have to calculate the maximum length of its odd proper suprefix.
Let's look at suprefix of fixed $k$-substring: we can't find its maximal length via binary search because this function isn't monotone in general case. But, by fixing not the left border but the center of the prefix, we also fix the center of the corresponding suffix (center of a prefix in position $i$ is tied with the center of the suffix in position $n + 1 - i$), and, more important, function becomes monotone. So solution is next: iterate over all valid centers of prefix $i$ and try to binary search maximal length $2x + 1$ of such substring that its center is in position $i$, and it's equal to the substing with center in $n + 1 - i$. $ans_{i - x}$ then can be updated with value $2x + 1$. And don't forget to update each $ans_{i}$ with value $ans_{i - 1} - 2$. Easy way to check substrings for equality is to use hashes. Harder way is to use string suffix structures (like bundle of Suffix Array + LCP + Sparse Table or Suffix Tree + LCA). Note for SuffArray users: don't forget about changing sort to stable_sort (merge sort) and breaking if all suffixes are different. This optimizations can save you from writing radix (or bucket) sort.
[ "binary search", "hashing", "string suffix structures" ]
2,700
#include <bits/stdc++.h> #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define all(a) (a).begin(), (a).end() #define sz(a) int(a.size()) #define mp make_pair #define x first #define y second using namespace std; typedef long long li; const li MOD = li(1e18) + 3; const li BASE = 1009; inline li norm(li a) { while(a >= MOD) a -= MOD; while(a < 0) a += MOD; return a; } inline li mul(li a, li b) { li m = ((long double)(a) * b) / MOD; return norm(a * b - m * MOD); } const int N = 1000 * 1000 + 555; int n; string s; inline bool read() { if(!(cin >> n)) return false; char buf[N]; assert(scanf("%s", buf) == 1); s = buf; return true; } li h[N], pw[N]; inline void precalc() { h[0] = 0; fore(i, 0, n) h[i + 1] = norm(mul(h[i], BASE) + s[i] - 'a' + 1); pw[0] = 1; fore(i, 1, N) pw[i] = mul(pw[i - 1], BASE); } inline li getHash(int l, int r) { return norm(h[r] - mul(h[l], pw[r - l])); } inline bool eq(int i1, int i2, int l) { if(i1 == i2) return true; return getHash(i1, i1 + l) == getHash(i2, i2 + l); } int l[N], mx[N]; inline void solve() { precalc(); fore(i, 0, n / 2) { int c1 = i, c2 = n - 1 - i; if(s[c1] != s[c2]) { l[i] = -1; continue; } int lf = 0, rg = min(c1, n - 1 - c2) + 1; while(rg - lf > 1) { int mid = (lf + rg) >> 1; if(eq(c1 - mid, c2 - mid, 2 * mid + 1)) lf = mid; else rg = mid; } l[i] = lf; } fore(i, 0, n / 2) { if(l[i] < 0) continue; mx[i - l[i]] = max(mx[i - l[i]], 2 * l[i] + 1); } fore(i, 1, n / 2) mx[i] = max(mx[i], mx[i - 1] - 2); fore(i, 0, (n + 1) / 2) { if(i) printf(" "); if(mx[i] == 0) mx[i] = -1; printf("%d", mx[i]); } puts(""); } int main(){ if(read()) { solve(); } return 0; }
961
G
Partitions
You are given a set of $n$ elements indexed from $1$ to $n$. The weight of $i$-th element is $w_{i}$. The weight of some subset of a given set is denoted as $W(S)=|S|\cdot\sum_{i\in S}w_{i}$. The weight of some partition $R$ of a given set into $k$ subsets is $W(R)=\sum_{S\in R}W(S)$ (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition). Calculate the sum of weights of all partitions of a given set into exactly $k$ \textbf{non-empty} subsets, and print it modulo $10^{9} + 7$. Two partitions are considered different iff there exist two elements $x$ and $y$ such that they belong to the same set in one of the partitions, and to different sets in another partition.
Let's look at some facts. At first, the answer is the sum of weights $w_{i}$ taken with some coefficients $cf_{i}$. So, it's enough to calculate those coefficients. Then $cf_{i}$ can be calculated by iterating on the size of the subset containing $i$-th element: $c f_{i}=\sum_{s i z e=1}^{s i z e=n+1-k}s i z e\cdot f(n,k,s i z e)$, where $f(n, k, size)$ is the number of partitions of set with $n$ elements into $k$ nonempty subsets with one subset of fixed size $size$ where $i$ belongs. This solution is still quite slow, so the next fact is: if two elements $i$ and $j$ belong to the same subset, then $j$ "increases" the coefficient before $w_{i}$. So for each element $i$ we can iterate over all elements $j$ which will lie in one subset with $i$. In other words, $c f_{i}=\sum_{i=1}^{\scriptscriptstyle{J=n}}g(n,k,i,j)=g(n,k,i,i)+\sum_{i\neq i}g(n,k,i,j)$. $g(n, k, i, j)$ is the number of ways to divide set with $n$ elements into $k$ subsets in such a way that elements $i$ and $j$ wil lie in one subset. $g(n, k, i, j)$ can be calculated using Stirling numbers of the second kind: let $\textstyle\{{}_{k}^{n}\}$ be the number of partitions of set with $n$ elements into $k$ non-empty subsets. If $i = j$ then $g(n,k,i,j)={\dot{\{}}_{k}^{n}\}$, else we just merge $i$ and $j$ into one element and let $g(n,k,i,j)={\binom{n-1}{k}}$. Final formula is $c f_{i}=\left\{{}_{k}^{n}\right\}+\sum_{j\neq i}\left\{{}^{n-1}\right\}=\left\{{}_{k}^{n}\right\}+\left(n-1\right)\cdot\left\{{}_{k}^{n-1}\right\}$. And the answer is $\sum_{i=1}^{n-n}w_{i}\cdot c f_{i}=c f_{0}\sum_{i=1}^{n-n}w$. Counting Stirling numbers can be done with inclusion-exclusion principle or by searching Wiki: $\{{}_{k}^{n}\}={\textstyle\frac{1}{k!}}\sum_{j=0}^{j=k}(-1)^{k+j}({}_{j}^{k})j^{n}$. Resulting complexity is $O(nlog(n))$.
[ "combinatorics", "math", "number theory" ]
2,700
#include <bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define forn(i, n) fore(i, 0, n) const int MOD = int(1e9) + 7; inline int norm(int a) { while(a >= MOD) a -= MOD; while(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; } const int N = 200 * 1000 + 555; int f[N], inf[N]; void precalc() { f[0] = inf[0] = 1; fore(i, 1, N) { f[i] = mul(f[i - 1], i); inf[i] = mul(inf[i - 1], binPow(i, MOD - 2)); } } int n, k, w[N]; inline bool read() { if(!(cin >> n >> k)) return false; forn(i, n) cin >> w[i]; return true; } inline int c(int n, int k) { if(k > n || n < 0) return 0; if(k == 0 || n == k) return 1; return mul(f[n], mul(inf[n - k], inf[k])); } inline int s(int n, int k) { if(n == 0) return k == 0; if(k == 0) return n == 0; int ans = 0, sg[2] = {1, MOD - 1}; forn(cnt, k) ans = norm(ans + mul(sg[cnt & 1], mul(c(k, cnt), binPow(k - cnt, n)))); return mul(ans, inf[k]); } inline void solve() { int sum = 0; forn(i, n) sum = norm(sum + w[i]); int s0 = s(n, k); int s1 = mul(n - 1, s(n - 1, k)); cout << mul(sum, norm(s0 + s1)) << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif precalc(); assert(read()); solve(); #ifdef _DEBUG cerr << "TIME = " << clock() << endl; #endif return 0; }
962
A
Equator
Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first. On the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems. Determine the index of day when Polycarp will celebrate the equator.
To solve the problem we need to know the total number of problems which Polycarp planned to solve. We count it in one iteration through the given array and save the total number of problems in the variable $sum$. After that, we will again iterate through the array and count the number of problems that Polycarp will solve on the first $i$ days. Let this sum is equal to $l$. We need to find the smallest $i$ for which it is true that $l \cdot 2 \ge sum$. This day will be the answer.
[ "implementation" ]
1,300
null
962
B
Students in Railway Carriage
There are $n$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of $a$ student-programmers and $b$ student-athletes. Determine the largest number of students from all $a+b$ students, which you can put in the railway carriage so that: - no student-programmer is sitting next to the student-programmer; - and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting. Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
We will iterate from the left to the right through the given string and take the maximal substrings consisting from the dots only (bounded by asterisks/string bounds). Let the length of the current such substring is $len$. If $len$ is even, in the places corresponding to this substring, you can put maximum $len / 2$ students of each type, simply alternating them. Considering remaining $a$ and $b$, you can put $\min(a, len / 2)$ student-programmers and $\min(b, len / 2)$ student-athletes in these places. If $len$ is odd, then in the places corresponding to this substring, you can put $(len + 1) / 2$ students of the one type and $len / 2$ students of the other type. If $a > b$, then you need to start put students from a student-programmer. So, $\ min(a, (len + 1) / 2)$ of student-programmers and $\ min(b, len / 2)$ of student-athletes can be put in this substring. Otherwise, you need to put students in the same way, but starting from a student-athlete. Also, you need to remember to maintain the number of remaining students $a$ and $b$ after processing the current substring and move on to the next substring consisting of the dots only.
[ "constructive algorithms", "greedy", "implementation" ]
1,300
null
962
C
Make a Square
You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros. Determine the minimum number of operations that you need to consistently apply to the given integer $n$ to make from it the square of some positive integer or report that it is impossible. An integer $x$ is the square of some positive integer if and only if $x=y^2$ for some positive integer $y$.
Consider the given integer as a string $s$. Use the masks to brute all possible ways to delete digits. Let the remaining integer for the current mask is a string $t$. If the first character of $t$ is zero, skip this mask. Otherwise, we revert the string $t$ into the integer $cur$. Now we need to check does the $cur$ is a square of some integer. It can be done in many ways, for example, by adding all the integer squares less than $2 \cdot 10^{9}$ into the $set$ (its size will be approximately equal to the square root of $2 \cdot 10^{9}$) and check that $cur$ is in this set. If this is the case, we should update the answer with the difference between the string $s$ and the string $t$, because this difference is equal to the number of deleted digits for the current mask.
[ "brute force", "implementation", "math" ]
1,400
null
962
D
Merge Equals
You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $2 \cdot x$). Determine how the array will look after described operations are performed. For example, consider the given array looks like $[3, 4, 1, 2, 2, 1, 1]$. It will be changed in the following way: $[3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1]$. If the given array is look like $[1, 1, 3, 1, 1]$ it will be changed in the following way: $[1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4]$.
To solve this problem we should use a set of pairs, let's call it $b$. We will store in it all the elements of the current array (the first number in the pair)and the positions of these elements in the current array (the second number in the pair). The first elements of pairs should have type long long, because the result of merging the array elements can become large and the type int will overflow. Initially, you need to put in $b$ all elements of the given array with their positions. While there are elements in $b$, we will perform the following algorithm. Let $x$ be a pair in the beginning of $b$. Then look at the next element of $b$. If it does not exist, the algorithm is complete. Otherwise, let the next element is equal to $y$. If $x.first \neq y.first$, then there is no pair number for the element $x.first$, which is in the position $x.second$, and it will never appear, because all elements can only increase. So, remove $x$ from $b$ and repeat the algorithm from the beginning. Otherwise, the number at the position $x.second$ will be deleted, and the number in the position $y.second$ will be double up. So, remove $x$ and $y$ from $b$, put $(y.first \cdot 2, y.second)$ in $b$ and repeat the algorithm from the beginning. For the convenience of restoring the answer, you can mark deleted positions of the given array in an additional array, so, in this case you need to mark $x.second$ as a deleted position.
[ "data structures", "implementation" ]
1,600
null
962
E
Byteland, Berland and Disputed Cities
The cities of Byteland and Berland are located on the axis $Ox$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $Ox$ there are three types of cities: - the cities of Byteland, - the cities of Berland, - disputed cities. Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected. The countries agreed to connect the pairs of cities with BNET cables in such a way that: - If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, - If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables. Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities. The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected. Each city is a point on the line $Ox$. It is technically possible to connect the cities $a$ and $b$ with a cable so that the city $c$ ($a < c < b$) is not connected to this cable, where $a$, $b$ and $c$ are simultaneously coordinates of the cities $a$, $b$ and $c$.
We will call the disputed cities - purple points, the cities of Byteland - blue points, and the cities of Berland - red points. If there are no any purple points among the given points, you just need to connect all the neighboring red points between each other and all the neighboring blue points with each other. Thus, the answer is the sum of the distances between the leftmost red point and the rightmost red point and between the leftmost blue point and the rightmost red point. Otherwise, you firstly should connect all the neighboring purple points with each other. Consider what you should do to connect the red points. All the red points to the left of the leftmost purple point should be connected as follows: first from the left with the second from the left, second from the left with the third from the left and so on. The rightmost of these red points should be connected to the leftmost purple point. All the red points to the right of the rightmost purple point are connected in a similar way. Consider all the gaps between the neighboring purple points, and all the red and blue points between them. They should be connected in one of two ways. The first way is to connect the left purple with the leftmost red, the rightmost red with the right purple, and also connect all the neighboring red dots. Similarly we should make for the blue points. Let the total length of the edges for such a connection is equal to $len_1$. The second way is to connect the left and right purple point. Now consider only the purple points and the red ones. All adjacent points need to be connected to each other, except those which are on the maximum distance from all other pairs. If there are several, then we do not connect any pair. Similarly we make for the purple and blue points. Let the total length of the edges for such a connection is equal to $len_2$. If $len_1 > len_2$ we should connect points from the current gap in the second way, otherwise, in the first.
[ "constructive algorithms", "greedy" ]
2,200
null
962
F
Simple Cycles Edges
You are given an undirected graph, consisting of $n$ vertices and $m$ edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself). A cycle in a graph is called a simple, if it contains each own vertex exactly once. So simple cycle doesn't allow to visit a vertex more than once in a cycle. Determine the edges, which belong to exactly on one simple cycle.
To solve this problem, it is good to know about fundamental set of cycles. Briefly, in the graph it is easy to select such a minimal set of cycles $C$ that any other cycle can be obtained as XOR of some subset of cycles from $C$. This set is also called the fundamental set of cycles. To find it in a connected graph, you can find any carcass and, alternately, independently add to this carcass each of the edges that are not entered into it. When each such edge is added to the carcass, its cycle closes. The set of these cycles is a fundamental set of cycles. Thus, if the graph is connected, then the size of the fundamental set of cycles is exactly $m-n+1$. It is easy to see that if an edge belongs to exactly one cycle from the fundamental set of cycles, then it belongs to exactly one simple cycle. We solve the problem independently for each connected component. For a connected component, it finds its carcass by a search in depth, and each edge that does not enter the search tree into the depth will close a cycle. We only take into account those cycles that do not intersect along the edges. We should print only them in the form of a set of edges. If the carcass was built with a search in depth, then each cycle represents a path from the vertex to the child (plus the reverse edge). Thus, the problem now is: a set of pairs of vertices (a vertex and its descendant) that specify a set of paths from top to bottom is given in the tree. It is required to select those paths that do not intersect with any other paths from this set. To find such ways quickly it is possible with help of DSU (system of non-intersecting subsets) on paths. On the edge, you should store the -1 mark or the path number to which it belongs. When passing the edges without marking, it should be marked by this path. When passing an edge with a mark, it is necessary to merge two paths into the DSU, because they intersect. After processing the path, for all the vertices of the path, the ancestor should be reassign to the top vertex of the path. Because if we do not make this we will repeatedly go through the same path. Using the following code, we find for each vertex its depth in the depth search tree and all the back edges (an array be): Using the following code, we process all paths (actually cycles), merging the intersecting ones. Let $pp$ - it is an original array of ancestors in depth search tree (because array $p$ has been changed by the code above). Now, it is sufficient to the answer to take such paths plus the corresponding reverse edge that do not intersect with others (that is, the size of the DSU component is 1): This problem has another solution, based on the allocation of the doubly connected components with the help of the corresponding linear algorithm.
[ "dfs and similar", "graphs", "trees" ]
2,400
null
962
G
Visible Black Areas
Petya has a polygon consisting of $n$ vertices. All sides of the Petya's polygon are parallel to the coordinate axes, and each two adjacent sides of the Petya's polygon are perpendicular. It is guaranteed that the polygon is simple, that is, it doesn't have self-intersections and self-touches. All internal area of the polygon (borders are not included) was painted in black color by Petya. Also, Petya has a rectangular window, defined by its coordinates, through which he looks at the polygon. A rectangular window can not be moved. The sides of the rectangular window are parallel to the coordinate axes. \begin{center} {\small Blue color represents the border of a polygon, red color is the Petya's window. The answer in this case is 2.} \end{center} Determine the number of black connected areas of Petya's polygon, which can be seen through the rectangular window.
First, lets build a graph that represents only part of the polygon that is inside the window, as well as borders of the window. Do do this, for each segment of the polygon, find the intersection of that segment with the window, and, if it still is a segment with non-zero length, add it to the graph (add both endpoints as vertices and the segment itself as an edge). Next, add four corners of the window as vertices. Last, connect all the points on each of the four borders of the window with edges. This way, we have a planar graph, and we can find faces in this graph which will represent all the connected areas inside the window, both belonging to the polygon and not. To count only those that belong to the polygon one can mark those oriented edges, that were created while intersecting polygon's segments with the window, as important. Only mark an edge if it is directed the same way as the corresponding segment of the polygon. This way, those faces of the graph that are to the left of important edges, are the ones belonging to the polygon. But there is one bad case - when no segment of the polygon intersects with the window. It such case, the window is either entirely outside of the polygon, or entirely inside of it. To check this, find number of intersections of the polygon with a ray starting from inside of the window. If the number of intersections is even, the window is outside of the polygon. If it is odd, the window is outside.
[ "data structures", "dsu", "geometry", "trees" ]
2,800
null
963
A
Alternating Sum
You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$. Find out the \textbf{non-negative} remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$. \textbf{Note that the modulo is unusual!}
Let $Z = \sum \limits_{i=0}^{k - 1} s_{i} a^{n - i} b^{i}$ and $q = (\frac{b}{a})^k$. Let's notice that according equality is true: $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i} = \sum \limits_{i=0}^{(n + 1) / k - 1} Z \cdot q^{i}$ We can easily get values of $Z$, $q$. We only have to count the value of geometric progression. Remember to handle the situation when $q = 1$. In this case it is not necessarily means that $a = b$.
[ "math", "number theory" ]
1,800
null
963
B
Destruction of a Tree
You are given a tree (a graph with $n$ vertices and $n - 1$ edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or determine that it is impossible.
If $n$ is even, then the answer is always $NO$, because such trees have odd degree, but we can destroy only even number of edges. For any odd $n$ the answer exists. Let's call $dfs(i)$ from subtree $i$ and destroy such nodes, that new subtree will be empty or for all alive nodes in connected component will be true, that they have odd degree. Realisation of this $dfs$: Call it from sons of $i$ and recount degree of $i$, if it is even we destroy all subtree. Assume, that after the destruction we have nonempty subtree. All nodes have odd degree, so amount of left nodes is even. So number of left edges is odd, but in start we have even count of edges, contradiction. That means, that we destroyed all nodes.
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
2,000
null
963
C
Cutting Rectangle
A rectangle with sides $A$ and $B$ is cut into rectangles with cuts parallel to its sides. For example, if $p$ horizontal and $q$ vertical cuts were made, $(p + 1) \cdot (q + 1)$ rectangles were left after the cutting. After the cutting, rectangles were of $n$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $a \times b$ and $b \times a$ are considered different if $a \neq b$. For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle. Calculate the amount of pairs $(A; B)$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $A$ and $B$. Note that pairs $(A; B)$ and $(B; A)$ are considered different when $A \neq B$.
There are a lot of ways to solve this problem. Let $a_i$ occurs in input $cnt_{a_{i}}$ (sum of $c$) times and $a_j$ occurs $cnt_{a_{j}}$. Then on a side of initial rectangle number of times $a_i$ occurs $/$ number of times $a_j$ occurs is a ratio $(cnt_{a_{i}}: cnt_{a_{j}})$. Analogically for $b$. Let's build the smallest rectangle which satisfies this ratio and call him the base one. Then initial rectangle should consist of it. The last step is to check that initial rectangle consists of base ones. To do this we'll iterate over all types of rectangles in input and if we find a mistake - print 0. In this way we will check no more than $n + 1$ types of recktangles. An answer for this task is number of divisors of ratio between the initial rectangle and the base one (it's not hard to see that this ratio equals to $GCD$ of all $c_i$)
[ "brute force", "math", "number theory" ]
2,600
null
963
D
Frequency of String
You are given a string $s$. You should answer $n$ queries. The $i$-th query consists of integer $k_i$ and string $m_i$. The answer for this query is the minimum length of such a string $t$ that $t$ is a substring of $s$ and $m_i$ has at least $k_i$ occurrences as a substring in $t$. A substring of a string is a continuous segment of characters of the string. It is guaranteed that for any two queries the strings $m_i$ from these queries are different.
Let $M$ be the summary length of $m_i$ Number of different lengths of $m_i$ is $O(\sqrt{M})$. All $m_i$ are distinct, so summary number of their entries in $s$ is $O(M\sqrt{M}))$. Let's find all entries of every $m_i$. To do this we can use Aho-Corasick's algorithm. Then we know entries of $m_i$, it is not hard to calculate the answer.
[ "hashing", "string suffix structures", "strings" ]
2,500
null
963
E
Circles of Waiting
A chip was placed on a field with coordinate system onto point $(0, 0)$. Every second the chip moves randomly. If the chip is currently at a point $(x, y)$, after a second it moves to the point $(x - 1, y)$ with probability $p_{1}$, to the point $(x, y - 1)$ with probability $p_{2}$, to the point $(x + 1, y)$ with probability $p_{3}$ and to the point $(x, y + 1)$ with probability $p_{4}$. It's guaranteed that $p_{1} + p_{2} + p_{3} + p_{4} = 1$. The moves are independent. Find out the expected time after which chip will move away from origin at a distance greater than $R$ (i.e. $x^{2}+y^{2}\!>R^{2}$ will be satisfied).
Let's call a sell "good", if for its coordinates the following condition is satisfied $x^{2} + y^{2} \le R^{2}$. For each good cell we consider the equation of its expected value: $f(x, y) = p_{1} \cdot f(x - 1, y) + p_{2} \cdot f(x, y + 1) + p_{3} \cdot f(x + 1, y) + p_{4} \cdot f(x, y - 1) + 1$. Then this problem can be reduced to solving the system of linear equations. We can do this using Gauss's method with a complexity of $O(R^{6})$, but this solution gets TL. Now, we can see that we only need to calculate $f(0, 0)$. So we will handle cells top down. While handling each row, we will relax values of all previous rows and a row of cell $(0;0)$. Also we will iterate only for non-zero elements of each row. This solution has a complexity of $O(R^{4})$. Prove of the complexity: Let's dye yellow all cells that we have already passed, green - all cells adjacent to them and black - all other cells. Then next cell which we will add is green. Note that its equation(for a moment of adding) doesn't include yellow cells. It consists of initially adjacent black cells and green cells. It's not hard to see, that then row includes only $O(R)$ non-zero elements and the current green cell is inside of $O(R)$ not visited rows. So one row in Gauss's method is handled in$O(R^{2})$ and there are $O(R^{2})$ rows. That's why this Gauss's method works in $O(R^{4})$.
[ "math" ]
3,100
null
964
A
Splits
Let's define a split of $n$ as a nonincreasing sequence of positive integers, the sum of which is $n$. For example, the following sequences are splits of $8$: $[4, 4]$, $[3, 3, 2]$, $[2, 2, 1, 1, 1, 1]$, $[5, 2, 1]$. The following sequences aren't splits of $8$: $[1, 7]$, $[5, 4]$, $[11, -3]$, $[1, 1, 4, 1, 1]$. The weight of a split is the number of elements in the split that are equal to the first element. For example, the weight of the split $[1, 1, 1, 1, 1]$ is $5$, the weight of the split $[5, 5, 3, 3, 3]$ is $2$ and the weight of the split $[9]$ equals $1$. For a given $n$, find out the number of different weights of its splits.
There are 2 cases: If weight of the split equals $n$, then the split consist of ones. Here we have only 1 option. Else maximum number in the split is more then 1. Then we can replace all maximum numbers with twos and the rest we split into ones and weight will be the same. So, here we have $\frac{n}{2}$ options. Answer for this problem is $\frac{n}{2}$ + 1.
[ "math" ]
800
null
964
B
Messages
There are $n$ incoming messages for Vasya. The $i$-th message is going to be received after $t_{i}$ minutes. Each message has a cost, which equals to $A$ initially. After being received, the cost of a message decreases by $B$ each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at $0$. Also, each minute Vasya's bank account receives $C·k$, where $k$ is the amount of received but unread messages. Vasya's messages are very important to him, and because of that he wants to have all messages read after $T$ minutes. Determine the maximum amount of money Vasya's bank account can hold after $T$ minutes.
Adding $C \cdot k$ to account is equivalent to adding $C$ to prices of all come, but not read messages. Then after every minute to every unread messages adds $C - B$. If $C - B$ is positive, then answer is maximum when we read all messages at the time $T$. Otherwise we should read every message at the time it comes.
[ "math" ]
1,300
null
965
A
Paper Airplanes
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes. A group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?
Each person should receive $\lceil \frac{n}{s} \rceil$ sheets. So, there should be at least $k \cdot \lceil \frac{n}{s} \rceil$ sheets in total, for them $\lceil \frac{k \cdot \lceil \frac{n}{s} \rceil}{p} \rceil$ packs are needed.
[ "math" ]
800
## This is a solution for problem make-planes # This is nk_ok.py # # @author: Nikolay Kalinin # @date: Mon, 23 Apr 2018 16:28:50 +0300 k, n, s, p = map(int, input().split()) sheets_per_person = (n + s - 1) // s sheets = k * sheets_per_person print((sheets + p - 1) // p)
965
B
Battleship
Arkady is playing Battleship. The rules of this game aren't really important. There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship. Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.
Let's compute for each cell four values: the number of cells where a part of the ship can be located to the right ($r$), to the left ($l$), up ($u$) and down ($d$), including the cell itself. Then, if $k > 1$, then there are $\min(k, \max(0, l + r - k)) + \min(k, \max(0, u + d - k))$ positions of the ship containing this cell, and if $k = 1$ it's easy to check whether this value is $1$ or $0$. After that you should just print the maximum among all cells. This solution works in $O(n^3)$.
[ "implementation" ]
1,300
## This is a solution for problem sea-battle-best-shot # This is nk_ok.py # # @author: Nikolay Kalinin # @date: Mon, 23 Apr 2018 16:48:18 +0300 n, k = map(int, input().split()) a = [] for i in range(n): a.append(input()) maxans = 0 xans = 0 yans = 0 for i in range(n): for j in range(n): curans = 0 l = 0 while l < k and i - l >= 0 and a[i - l][j] == '.': l += 1 r = 0 while r < k and i + r < n and a[i + r][j] == '.': r += 1 curans += max(0, r + l - k) if k != 1: l = 0 while l < k and j - l >= 0 and a[i][j - l] == '.': l += 1 r = 0 while r < k and j + r < n and a[i][j + r] == '.': r += 1 curans += max(0, r + l - k) if curans > maxans: maxans = curans xans = i yans = j print("{} {}".format(xans + 1, yans + 1))
965
C
Greedy Arkady
$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away. The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away. Arkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting. Please find what is the maximum number of candies Arkady can receive by choosing some valid $x$.
As the limits on $D$ are small, let's try all possible values of $d$ - the number of times Arkady will receive candies. For a given $d$ it's easy to compute $x_{min}$ and $x_{max}$ - the maximum and minimum values of $x$ that suit these $d$ and $M$. Then, with a fixed $d$ it's easy to write the formula of how many candies Arkady gets: it's $x \cdot d$ candies. So it's obvious that we should choose $x_{max}$ for the given $d$ and update the answer. Bonus 1: can you solve the task when the leftover is not thrown away, but is given to the next person? Bonus 2: can you solve the task from bonus 1, but without the $D \le 1000$ condition (just $1 \le D \le n$)?
[ "math" ]
2,000
## This is a solution for problem candies-splitting # This is nk_ok.py # # @author: Nikolay Kalinin # @date: Mon, 23 Apr 2018 21:58:46 +0300 n, k, M, D = map(int, input().split()) ans = 0 for d in range(1, D + 1): # (d - 1) * k * x + x <= n maxx = M maxx = min(n // ((d - 1) * k + 1), maxx) if maxx == 0: continue reald = (n // maxx + k - 1) // k if reald != d: continue def f(x): return x * (d - 1) + x ans = max(ans, f(maxx)) print(ans)
965
D
Single-use Stones
A lot of frogs want to cross a river. A river is $w$ units width, but frogs can only jump $l$ units long, where $l < w$. Frogs can also jump on lengths shorter than $l$. but can't jump longer. Hopefully, there are some stones in the river to help them. The stones are located at integer distances from the banks. There are $a_i$ stones at the distance of $i$ units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water. What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
This problem can be solved using many different approaches, most of them are based on different greedy solutions. We will discuss a solution with an easy-provable greedy. First, let's do binary search for the answer. Let it be $k$. Then, assume that the stones are given by their positions $x_1, x_2, \ldots, x_m$, where $m$ is the total number of stones. Also assume $x_0 = 0$ and $x_{m+1} = w$ - the banks. Then, if for some $i$ the condition $x_{i+k} - x_i \le l$ is not satisfied, then $k$ frogs can't cross the river. Indeed, consider the first jump for each frog that ends at a position further than $x_i$. It can't end at $x_{i+k}$ or further because of the length of the jump, so it has to end at some stone at $x_{i+1}$, $x_{i+2}$, ..., or $x_{i+k-1}$. But there are only $k - 1$ such stones, so some stone is used by two frogs which is prohibited. Now, if $x_{i+k} - x_i \le l$ is satisfied, the frogs can easily cross the river by using the route $0 \to x_i \to x_{i+k} \to x_{i + 2k} \to \ldots$ for the $i$-th frog. So, the solution is to do the binary search for the answer and then compute the maximum distance between stones $x_{i+k}$ and $x_i$. This can be done using two pointers technique.
[ "binary search", "flows", "greedy", "two pointers" ]
1,900
/** * This line was copied from template * This is nk_ok.cpp * * @author: Nikolay Kalinin * @date: Mon, 23 Apr 2018 23:38:49 +0300 */ #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second const int maxn = 100005; const int inf = 1e9 + 9; int a[maxn]; int w, len; bool can(int k) { // cout << "can " << k << endl; int curj = 0; int j = 0; int curdiff = 0; for (int i = 0; i < w; i++) { while ((curdiff < k - 1 || a[j] == 0) && j < w) { if (curdiff + a[j] - curj <= k - 1) { curdiff += a[j] - curj; curj = 0; j++; } else { curj += k - 1 - curdiff; curdiff = k - 1; } // cout << "at " << i << ' ' << j << ' ' << curj << endl; } if (j > i + len) return false; curdiff -= a[i + 1]; if (j == w) break; } return true; } int main() { scanf("%d%d", &w, &len); for (int i = 1; i < w; i++) scanf("%d", &a[i]); a[w] = 1; int l = 0; int r = inf; while (r - l > 1) { int m = (l + r) / 2; if (can(m)) l = m; else r = m; } cout << l << endl; return 0; }
965
E
Short Code
Arkady's code contains $n$ variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code. He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names. A string $a$ is a prefix of a string $b$ if you can delete some (possibly none) characters from the end of $b$ and obtain $a$. Please find this minimum possible total length of new names.
First, let's construct a trie of the names. Now a name is a token on some node in the graph, and we can move the token freely up to the root with the only constraint that no two tokens share the same node. We have to minimize the total depth of the nodes with tokens. For each subtree let's compute the optimal positions of tokens that were initially in the subtree assuming that no token moves higher than the root of the subtree. It can be done easily with dynamic programming: if the current note has a token initially, then the answer is simply the union of this node and all the answers for the children. Otherwise, one of the tokens from children's answer should be moved to the current node. Obviously, it is the token with the highest depth. We can easily maintaining this using sets and smaller-to-larger optimization. This solution runs in $O(m \log^2{m})$, where $m$ is the total length of the strings. Also, due to the specific structure of the tree (because it is a trie and there is a constraint on the total length of the strings), we can do the same simulation without any data structures in $O(m)$ time.
[ "data structures", "dp", "greedy", "strings", "trees" ]
2,200
/** * This line was copied from template * This is nk_ok.cpp * * @author: Nikolay Kalinin * @date: Tue, 24 Apr 2018 19:13:31 +0300 */ #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second struct tnode { tnode *go[26]; bool term; tnode() { for (int i = 0; i < 26; i++) go[i] = NULL; term = false; } }; using pnode = tnode*; pnode root; char s[100005]; int n; void add() { pnode cur = root; char *t = s; while (*t != '\0') { if (cur->go[*t - 'a'] == NULL) cur->go[*t - 'a'] = new tnode(); cur = cur->go[*t - 'a']; t++; } cur->term = true; } using tans = multiset<int>; using pans = tans*; pans merge(pans a, pans b) { if (a->size() > b->size()) swap(a, b); for (auto t : *a) b->insert(t); delete a; return b; } pans calc(pnode cur, int curd) { pans ans = new tans; for (int i = 0; i < 26; i++) if (cur->go[i] != NULL) { auto t = calc(cur->go[i], curd + 1); ans = merge(ans, t); } if (cur->term) ans->insert(curd); else if (curd != 0) { ans->erase(prev(ans->end())); ans->insert(curd); } return ans; } int main() { root = new tnode(); scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%s", s); add(); } auto ans = calc(root, 0); // for (auto t : *ans) cout << t << ' '; // cout << endl; cout << accumulate(all(*ans), 0) << endl; return 0; }
967
A
Mind the Gap
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $1$ minute. He was asked to insert one takeoff in the schedule. The takeoff takes $1$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $s$ minutes from both sides. Find the earliest time when Arkady can insert the takeoff.
This problem requires you to carefully read and understand the statement. First, scan all the landing times, transforming each $h$ and $m$ pair into the number of minutes from the starting moment $60h + m$. Then, there are three possibilities: The first plane takes of not earlier than $s + 1$ minutes from now. In this case we may put new takeoff right now. Otherwise, if there is a pair of planes with at least $2 + 2s$ minutes between them. In this case we may choose the earliest such pair and put a new takeoff at $1 + s$ minutes after the first of these planes. Otherwise, we may always put a new plane in $1 + s$ minutes after the last plane. Finally, print the answer in an $h~m$ format.
[ "implementation" ]
1,100
null
967
B
Watering System
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it. What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
It's obvious that we should block several largest holes. Let's first sort them. After that, let's iterate through the number of blocked holes, maintaining the sum of sizes of non-blocked holes $S$. With the value $S$ it is easy to compute if the flow from the first hole is large enough or not. Just output the number of blocked pipes at the first moment when the flow is large enough. The complexity is $O(n)$.
[ "math", "sortings" ]
1,000
null
975
A
Aramic script
In Aramic language words can only represent objects. Words in Aramic have special properties: - A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of \textbf{different objects} mentioned in the script?
One can easily notice that we only differentiate between words when different letters exit, so one easy way to consider all the different words that belong to the same root as one, is to map every word to a mask of 26 bits; that is, for example, if letter 'b' exits in the ith word then we set the second bit in the ith mask to one, eventually, we insert all the masks in a set and the set size is the required answer.
[ "implementation", "strings" ]
900
"#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sc(a) scanf(\"%d\",&a)\n#define scs(a) scanf(\" %s\",a)\n\n\ntypedef long long ll;\n\nconst int MAX = 1e3 + 11;\n\nchar in[MAX];\nset<int> s;\n\nint main()\n{\n int n;\n sc(n);\n\n for(int i=0;i<n;++i)\n {\n scs(in);\n int l = strlen(in);\n int cur = 0;\n for(int j=0;j<l;++j)\n cur = cur | (1<<(in[j]-'a'));\n s.insert(cur);\n }\n\n cout<<s.size();\n\n return 0;\n}"
975
B
Mancala
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a \textbf{positive} number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction. Note that the counter-clockwise order means if the player takes the stones from hole $i$, he will put one stone in the $(i+1)$-th hole, then in the $(i+2)$-th, etc. If he puts a stone in the $14$-th hole, the next one will be put in the first hole. After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli. Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
in this problem, we brute-force on the optimal hole to choose since there are only 14 holes, but how to calculate how many stones there will be after we start from the ith hole? the process of putting stones is repeating every 14 holes, suppose k is the number of stones in hand now so k/14 will be added to all holes and we simulate adding k mod 14 then we take the maximum answer from all the holes.
[ "brute force", "implementation" ]
1,100
"#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sc(a) scanf(\"%lld\",&a)\n\ntypedef long long ll;\n\nconst int MAX = 5e3 + 11;\n\nll a[22];\nll pro[22];\n\nint main()\n{\n for(int i=0;i<14;++i)\n sc(a[i]);\n\n ll res = 0;\n\n for(int i=0;i<14;++i)\n {\n for(int j=0;j<14;++j)\n pro[j] = a[j];\n ll tmp = pro[i];\n pro[i] = 0;\n for(int j=0;j<14;++j)\n pro[j] += tmp/14;\n tmp %= 14;\n int k = i+1;\n while(tmp--)\n {\n if(k == 14)\n k = 0;\n pro[k++]++;\n }\n ll score = 0;\n for(int j=0;j<14;++j)\n {\n if(pro[j] & 1)\n continue;\n score += pro[j];\n }\n res = max(res,score);\n }\n\n cout<<res;\n\n\n return 0;\n}"
975
C
Valhalla Siege
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle. Ivar has $n$ warriors, he places them on a straight line in front of the main gate, in a way that the $i$-th warrior stands right after $(i-1)$-th warrior. The first warrior leads the attack. Each attacker can take up to $a_i$ arrows before he falls to the ground, where $a_i$ is the $i$-th warrior's strength. Lagertha orders her warriors to shoot $k_i$ arrows during the $i$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $t$, they will all be standing to fight at the end of minute $t$. The battle will last for $q$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.
naive simulations will get TLE, so how to calculate fast how many people are going to die after the ith query, we can binary search on the prefix sum. Thus, we can tell how many people are going to die in O(log n) per query. Note: beware to handle the queries that do a partial damage for some warrior and include that partial damage in the later queries.
[ "binary search" ]
1,400
"#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sc(a) scanf(\"%d\",&a)\n#define scll(a) scanf(\"%lld\",&a)\n\ntypedef long long ll;\n\nconst int MAX = 2e5 + 11;\n\nll a[MAX],csum[MAX];\nint n;\n\nint bs(int pos,ll &hits,ll val)\n{\n if(val + hits < a[pos])\n {\n hits += val;\n return pos;\n }\n int st = pos,en = n;\n int ret;\n while(st <= en)\n {\n int md = (st + en)>>1;\n if(csum[md] - csum[pos - 1] - hits <= val)\n st = md + 1,ret = md;\n else\n en = md - 1;\n }\n if(ret == n)\n {\n hits = 0;\n return 1;\n }\n ret++;\n ll tmp = csum[ret] - csum[pos - 1] - hits - val;\n hits = a[ret] - tmp;\n return ret;\n}\n\nint main()\n{\n int q;\n sc(n);\n sc(q);\n\n ll sm = 0;\n\n for(int i=1;i<=n;++i)\n {\n scll(a[i]);\n csum[i] = csum[i - 1] + a[i];\n }\n\n int cur = 1;\n ll hits = 0;\n\n for(int i=0;i<q;++i)\n {\n ll x;\n scll(x);\n cur = bs(cur,hits,x);\n printf(\"%d\\n\",n - cur + 1);\n }\n\n return 0;\n}"
975
D
Ghosts
Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way. There are $n$ ghosts in the universe, they move in the $OXY$ plane, each one of them has its own velocity that does not change in time: $\overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j}$ where $V_{x}$ is its speed on the $x$-axis and $V_{y}$ is on the $y$-axis. A ghost $i$ has experience value $EX_i$, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time. As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind $GX = \sum_{i=1}^{n} EX_i$ will never increase. Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time $T$, and magically all the ghosts were aligned on a line of the form $y = a \cdot x + b$. You have to compute what will be the experience index of the ghost kind $GX$ in the indefinite future, this is your task for today. Note that when Tameem took the picture, $GX$ may already be greater than $0$, because many ghosts may have scared one another at any moment between $[-\infty, T]$.
The condition for two points to meet in a moment of time T is for them to have the same X coordinates and the same Y coordinates. Time when they have the same X coordinates is $X_{0i} + V_{xi} T_x = X_{0j} + V_{xj} T_x$ So $T_x$ should be $T_x = (X_{0i} - X_{0j})/ (V_{xj} - V_{xi})$ Time when they will meet on Y axis $T_y = (aX_{0i} - aX_{0j} + b -b)/ (V_{yj} - V_{yi})$ In order for them to collide $T_y = T_x$ so $(X_{0i} - X_{0j})/ (V_{xj} - V_{xi}) = (aX_{0i} - aX_{0j} + b -b)/ (V_{yj} - V_{yi})$ so $1/(V_{xj} - V_{xi}) = a/(V_{yj} - V_{yi})$ So $a V_{xj} - V_{yj} = a V_{xi} - V_{yi}$ Meaning that all ghosts with the same $a V_{x} - V_{y}$ will collide except if they were parallel. the answer is two times the number of collisions.
[ "geometry", "math" ]
2,000
"#include <bits/stdc++.h>\nconst int MX = 2e5+5;\nusing namespace std;\ntypedef long long ll;\nint main() {\n int n;cin>>n;ll a,b;cin>>a>>b;\n map<ll,ll> vis;\n map<pair<int,int>,int> sim;\n ll ans = 0;\n for(int i=1;i<=n;i++)\n {\n int x,vx,vy;\n scanf(\"%d%d%d\",&x,&vx,&vy);\n ans += vis[a*vx-vy] - sim[{vx,vy}];\n vis[a*vx-vy]++;\n sim[{vx,vy}]++;\n }\n cout<<2*ans<<endl;\n}"
975
E
Hag's Khashba
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering. Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance. Hag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a \textbf{strictly convex} polygon with $n$ vertices. Hag brought two pins and pinned the polygon with them in the $1$-st and $2$-nd vertices to the wall. His dad has $q$ queries to Hag of two types. - $1$ $f$ $t$: pull a pin from the vertex $f$, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex $t$. - $2$ $v$: answer what are the coordinates of the vertex $v$. Please help Hag to answer his father's queries. You can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.
In this problem, we calculate the center of mass of the polygon (ie its centroid) and then we make it our reference point. we maintain its coordinates after each and every rotation. Now when the pin is taken out from a vertex it leaves the other pin as a pivot for rotation we calculate the angle of current rotation. calculate the new coordinates of the center of mass after rotation, we should also store the initial distances from the center of mass, and the angle that the polygon had rotated around itself. from the angle, coordinates of the center of mass and the initial distances from the center of mass it is possible to calculate the coordinates of any point in the polygon. Note: when calculating the center of mass we should shift the polygon to the (0,0) because in some algorithms it uses point (0,0) in triangulation the polygon. if the polygon is very far from (0,0) accuracy will be lost. so better to either shift the polygon to (0,0) or use the first point of the polygon to form the sub-triangles of the polygon when calculating the center of mass.
[ "geometry" ]
2,600
"#include <algorithm>\n#include <bitset>\n#include <complex>\n#include <cassert>\n#include <deque>\n#include <iostream>\n#include <iomanip>\n#include <istream>\n#include <iterator>\n#include <map>\n#include <math.h>\n#include <memory>\n#include <ostream>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <string.h>\n#include <time.h>\n#include <vector>\n\n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 4000000000000000000LL\n#define INF 1000000000\n#define EPS 1e-8\n#define LL long long\n#define mod 1000000007\n#define pb push_back\n#define mp make_pair\n#define f first\n#define s second\n#define setzero(a) memset(a,0,sizeof(a))\n#define setdp(a) memset(a,-1,sizeof(a))\n#define bits(a) __builtin_popcountll(a)\n\nusing namespace std;\n\ntypedef pair<long double, long double> point;\n\nconst long double PI = acosl(-1);\n\npoint arr[200009];\nlong double dist[200009], ang[200009];\n\npoint get_centroid(int n) {\n long double area = 0.0, tmp;\n point a, b, res = point(0, 0);\n for (int i = 0; i < n; i++) {\n a = arr[i], b = arr[(i + 1) % n];\n tmp = a.f * b.s - b.f * a.s;\n area += tmp;\n res.f += (a.f + b.f) * tmp;\n res.s += (a.s + b.s) * tmp;\n }\n area *= 0.5;\n res.f /= (area * 6);\n res.s /= (area * 6);\n return res;\n}\n\npoint get(int ind, const point &centroid, const double &angle) {\n point ans;\n ans.f = centroid.f + dist[ind] * cosl(angle + ang[ind]);\n ans.s = centroid.s + dist[ind] * sinl(angle + ang[ind]);\n return ans;\n}\n\nlong double get_dist(const point &a, const point &b) {\n return sqrtl((a.f - b.f) * (a.f - b.f) + (a.s - b.s) * (a.s - b.s));\n}\n\nint main() {\n int n, q;\n double a, b;\n cin >> n >> q;\n for (int i = 0; i < n; i++) {\n scanf(\"%lf %lf\", &a, &b);\n arr[i] = point(a, b);\n }\n long double zbx=arr[0].first,zby=arr[0].second;\n for(int i=0; i < n; i++)\n {\n arr[i].first-=zbx;\n arr[i].second-=zby;\n }\n int i = 0, j = 1, c, x, y;\n point centroid = get_centroid(n), top, nxt;\n long double angle = 0;\n for (int i = 0; i < n; i++) {\n dist[i] = get_dist(arr[i], centroid);\n ang[i] = atan2l(arr[i].s - centroid.s, arr[i].f - centroid.f);\n if (ang[i] < 0)\n ang[i] += 2 * PI;\n }\n while (q--) {\n scanf(\"%d\", &c);\n if (c == 1) {\n scanf(\"%d %d\", &x, &y);\n x--, y--;\n if (x == i) {\n i = y;\n top = get(j, centroid, angle);\n nxt = point(top.f, top.s - dist[j]);\n } else {\n j = y;\n top = get(i, centroid, angle);\n nxt = point(top.f, top.s - dist[i]);\n }\n angle += -PI / 2 - atan2l(centroid.s - top.s, centroid.f - top.f);\n while (angle < 0)\n angle += 2 * PI;\n while (angle > 2 * PI)\n angle -= 2 * PI;\n centroid = nxt;\n } else {\n scanf(\"%d\", &x);\n top = get(x - 1, centroid, angle);\n printf(\"%.10lf %.10lf\\n\", (double) (top.f+zbx), (double) (top.s+zby));\n }\n }\n return 0;\n}"
976
A
Minimum Binary Number
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string $s$. You can perform two different operations on this string: - swap any pair of adjacent characters (for example, "{1\underline{01}}" $\to$ "{1\underline{10}}"); - replace "11" with "1" (for example, "{\underline{11}0}" $\to$ "{\underline{1}0}"). Let $val(s)$ be such a number that $s$ is its binary representation. Correct string $a$ is less than some other correct string $b$ iff $val(a) < val(b)$. Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).
If $n = 1$ then the answer is equal to $s$. Otherwise answer will be equal to $2^{cnt0}$, where $cnt_{0}$ is the count of the zeroes in the given string (i.e. the answer is the binary string of length $cnt_{0} + 1$, in which the first character is one and the other characters are zeroes).
[ "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 n; string s; cin >> n >> s; if (n == 1) { cout << s << endl; } else { int cnt0 = 0; for (int i = 0; i < n; ++i) cnt0 += s[i] == '0'; cout << 1; for (int i = 0; i < cnt0; ++i) cout << 0; cout << endl; } return 0; }
976
B
Lara Croft and the New Game
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of $n$ rows and $m$ columns. Cell $(x, y)$ is the cell in the $x$-th row in the $y$-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell $(1, 1)$, that is top left corner of the matrix. Then she goes down all the way to cell $(n, 1)$ — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in $2$-nd column, one cell up. She moves until she runs out of non-visited cells. $n$ and $m$ given are such that she always end up in cell $(1, 2)$. Lara has already moved to a neighbouring cell $k$ times. Can you determine her current position?
Naive solution would be just simulate the tranversal and break when $k$ steps are made. Obviously, this won't fit into time limit. Then we can decompose the path to some parts which can be calculated separately. Walk from the top left to the bottom left corner; Walk from second column to $m$-th on even rows; Walk from $m$-th column to second on odd rows. If $k < n$ then it's the first part. Otherwise you can use the fact that rows are of the same length. $(k - n)div(m - 1)$ will tell you the row and $(k - n)mod(m - 1)$ will get you the number of steps Lara have made along this row. Overall complexity: $O(1)$.
[ "implementation", "math" ]
1,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n, m; long long k; int main() { scanf("%d%d%lld", &n, &m, &k); if (k < n){ printf("%lld 1\n", k + 1); return 0; } k -= n; long long row = k / (m - 1); printf("%lld ", n - row); if (row & 1) printf("%lld\n", m - k % (m - 1)); else printf("%lld\n", k % (m - 1) + 2); return 0; }
976
C
Nested Segments
You are given a sequence $a_{1}, a_{2}, ..., a_{n}$ of one-dimensional segments numbered $1$ through $n$. Your task is to find two distinct indices $i$ and $j$ such that segment $a_{i}$ lies within segment $a_{j}$. Segment $[l_{1}, r_{1}]$ lies within segment $[l_{2}, r_{2}]$ iff $l_{1} ≥ l_{2}$ and $r_{1} ≤ r_{2}$. Print indices $i$ and $j$. If there are multiple answers, print any of them. If no answer exists, print -1 -1.
Let's sort segments firstly by their left border in increasing order and in case of equal by their right border in decreasing order. If there is any valid pair then the inner segment will always go after the outer one. Now you can go from left to right, keep the maximum right border of processed segments and compare it to the current segment. Overall complexity: $O(n\cdot\log n)$.
[ "greedy", "implementation", "sortings" ]
1,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define x first #define y second using namespace std; typedef pair<int, int> pt; const int N = 300 * 1000 + 13; int n; pair<pt, int> a[N]; int main() { scanf("%d", &n); forn(i, n){ scanf("%d%d", &a[i].x.x, &a[i].x.y); a[i].y = i + 1; } sort(a, a + n, [&](pair<pt, int> a, pair<pt, int> b){if (a.x.x != b.x.x) return a.x.x < b.x.x; return a.x.y > b.x.y;}); set<pt> cur; forn(i, n){ while (!cur.empty() && cur.begin()->x < a[i].x.x) cur.erase(cur.begin()); if (!cur.empty() && (--cur.end())->x >= a[i].x.y){ printf("%d %d\n", a[i].y, (--cur.end())->y); return 0; } cur.insert({a[i].x.y, a[i].y}); } puts("-1 -1"); return 0; }
976
D
Degree Set
You are given a sequence of $n$ positive integers $d_{1}, d_{2}, ..., d_{n}$ ($d_{1} < d_{2} < ... < d_{n}$). Your task is to construct an undirected graph such that: - there are exactly $d_{n} + 1$ vertices; - there are no self-loops; - there are no multiple edges; - there are no more than $10^{6}$ edges; - its degree set is equal to $d$. Vertices should be numbered $1$ through $(d_{n} + 1)$. Degree sequence is an array $a$ with length equal to the number of vertices in a graph such that $a_{i}$ is the number of vertices adjacent to $i$-th vertex. Degree set is a sorted in increasing order sequence of all distinct values from the degree sequence. It is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than $10^{6}$ edges. Print the resulting graph.
We prove that the answer always always exists by constructing it. Graph for $n = 0$ is a single vertex; Graph for $n = 1$ is a clique of $d_{1} + 1$ vertices; Graph for some $(d_{1}, d_{2}, ..., d_{k})$ is obtained from the graph $(d_{2} - d_{1}, d_{3} - d_{1}, ..., d_{k - 1} - d_{1})$ by adding $(d_{k} - d_{k - 1})$ vertices initially connected to nothing and $d_{1}$ vertices connected to all previously mentioned ones. The vertices connected to nothing got degrees $d_{1}$, the vertices from the previous step increased their degrees by $d_{1}$ and finally there appeared vertices of degree $d_{k}$. The number is vertices is $d_{k} + 1$ as needed.
[ "constructive algorithms", "graphs", "implementation" ]
2,500
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; typedef pair<int, int> pt; const int N = 100 * 1000 + 13; int n; vector<int> d; vector<int> g[N]; vector<pt> construct(int st, vector<int> d){ if (d.empty()) return vector<pt>(); vector<pt> res; forn(i, d[0]) for (int j = st + i + 1; j <= st + d.back(); ++j) res.push_back({st + i, j}); int nxt = st + d[0]; for (int i = 1; i < int(d.size()); ++i) d[i] -= d[0]; d.erase(d.begin()); if (!d.empty()) d.pop_back(); auto tmp = construct(nxt, d); for (auto it : tmp) res.push_back(it); return res; } int main() { scanf("%d", &n); d.resize(n); forn(i, n) scanf("%d", &d[i]); auto res = construct(0, d); printf("%d\n", int(res.size())); for (auto it : res) printf("%d %d\n", it.first + 1, it.second + 1); return 0; }
976
E
Well played!
Recently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them: Max owns $n$ creatures, $i$-th of them can be described with two numbers — its health $hp_{i}$ and its damage $dmg_{i}$. Max also has two types of spells in stock: - Doubles health of the creature ($hp_{i}$ := $hp_{i}·2$); - Assigns value of \textbf{health} of the creature to its \textbf{damage} ($dmg_{i}$ := $hp_{i}$). Spell of first type can be used no more than $a$ times in total, of the second type — no more than $b$ times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells. Max is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way.
At first let's prove that in optimal solution all spells of 1-st type are assigned to single creature. By contradiction: let's optimal answer contains indices $i \neq j$ where $hp'_{i} = hp_{i} \cdot 2^{x}$ and $hp'_{j} = hp_{j} \cdot 2^{y}$. If $hp'_{i(j)} \le dmg_{i(j)}$ using spells of 1-st type is meaningless. Otherwise, if (in general case) $hp'_{i} \ge hp'_{j}$ then $hp_{i} \cdot 2^{x + 1} + hp_{j} \cdot 2^{y - 1} > hp'_{i} + hp'_{j}$. Contradiction. So, we can check for each creature maximal damage with its health multiplied. At second, if we sort all creatures in order by decreasing $(hp_{i} - dmg_{i})$, using $b$ spells on first $b$ creatures gives best answer $ans$. So, calculating answer for chosen creature invokes 2 cases: if chosen creature is belong to first $b$ creatures, then subtract from $ans$ its contribution, calculate new value and add it to $ans$; otherwise, we need one spell of second type, which is optimal to take from $b$-th creature, so along with replacing old value of chosen one we need to replace in $ans$ contribution of $b$-th creature. Result complexity is $O(n \cdot log(n))$
[ "greedy", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 9; int n, a, b; int hp[N], dmg[N]; bool cmp(int i, int j){ if(hp[i] - dmg[i] != hp[j] - dmg[j]) return hp[i] - dmg[i] > hp[j] - dmg[j]; return i < j; } int get(int id){ return hp[id] > dmg[id]? hp[id] : dmg[id]; } int main(){ scanf("%d %d %d", &n, &a, &b); for(int i = 0; i < n; ++i) scanf("%d %d", hp + i, dmg + i); b = min(b, n); vector <int> p(n); for(int i = 0; i < n; ++i) p[i] = i; sort(p.begin(), p.end(), cmp); long long res = 0, sum = 0; for(int i = 0; i < n; ++i){ int id = p[i]; if(i < b) sum += get(id); else sum += dmg[id]; } res = sum; if(b == 0){ printf("%lld\n", res); return 0; } long long x = (1LL << a); for(int i = 0; i < n; ++i){ int id = p[i]; long long nres = sum; if(i < b){ nres -= get(id); nres += hp[id] * x; res = max(res, nres); } else{ nres -= dmg[id]; nres += hp[id] * x; int id2 = p[b - 1]; nres -= get(id2); nres += dmg[id2]; res = max(res, nres); } } printf("%lld\n", res); return 0; }
976
F
Minimal k-covering
You are given a bipartite graph $G = (U, V, E)$, $U$ is the set of vertices of the first part, $V$ is the set of vertices of the second part and $E$ is the set of edges. There might be multiple edges. Let's call some subset of its edges $\bar{E}$ $k$-covering iff the graph ${\bar{G}}=(U,V,{\bar{E}})$ has each of its vertices incident to at least $k$ edges. Minimal $k$-covering is such a $k$-covering that the size of the subset $\bar{E}$ is minimal possible. Your task is to find minimal $k$-covering for each $k\in[0..m i n D e g r e e]$, where $minDegree$ is the minimal degree of any vertex in graph $G$.
To get the answer for some $k$ we can build the following network: connect the source to every vertex of the first part with edge with capacity $deg_{x} - k$ (where $deg_{x}$ is the degree of vertex), then transform every edge of the original graph into a directed edge with capacity $1$, and then connect each vertex from the second part to the sink with capacity $deg_{x} - k$. Then edges saturated by the maxflow are not present in the answer (and all other edges are in the answer). To solve it fastly, we might just iterate on $k$ from its greatest value to $0$ and each time augment the flow we found on previous iteration. Since maxflow in the network is at most $m$, and we will do not more than $m$ searches that don't augment the flow, this solution is $O((n + m)^{2})$.
[ "flows", "graphs" ]
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 const int INF = int(1e9); const int N = 4221; struct edge { int to, c, f, id; edge(int to = 0, int c = 0, int f = 0, int id = -1) : to(to), c(c), f(f), id(id) {} }; vector<edge> es; vector<int> g[N]; void add_edge(int fr, int to, int cap, int id) { g[fr].push_back(sz(es)); es.emplace_back(to, cap, 0, id); g[to].push_back(sz(es)); es.emplace_back(fr, 0, 0, id); } int pw[N]; int n1, n2, m; inline bool read() { if(!(cin >> n1 >> n2 >> m)) return false; fore(id, 0, m) { int u, v; assert(cin >> u >> v); u--, v--; pw[u]++; pw[n1 + v]++; add_edge(u, n1 + v, 1, id); } return true; } int d[N], q[N], hd, tl; inline bool bfs(int s, int t, int n) { fore(i, 0, n) d[i] = INF; hd = tl = 0; d[s] = 0; q[tl++] = s; while(hd != tl) { int v = q[hd++]; if(v == t) break; for(int id : g[v]) { if(es[id].c - es[id].f == 0) continue; int to = es[id].to; if(d[to] > d[v] + 1) { d[to] = d[v] + 1; q[tl++] = to; } } } return d[t] < INF; } int nxt[N]; int dfs(int v, int t, int mx) { if(v == t) return mx; if(mx == 0) return 0; int sum = 0; for(; nxt[v] < sz(g[v]); nxt[v]++) { int id = g[v][nxt[v]]; int rem = es[id].c - es[id].f; int to = es[id].to; if(rem == 0 || d[to] != d[v] + 1) continue; int cur = 0; if((cur = dfs(to, t, min(mx - sum, rem))) > 0) { es[id].f += cur; es[id ^ 1].f -= cur; sum += cur; } if(sum == mx) break; } return sum; } inline int dinic(int s, int t, int n) { int mf = 0; while(bfs(s, t, n)) { fore(i, 0, n) nxt[i] = 0; int cf = 0; while((cf = dfs(s, t, INF)) > 0) mf += cf; } return mf; } vector<int> res[N]; inline void getCert(int k) { fore(v, 0, n1) { for(int id : g[v]) { if(es[id].to < n1 || es[id].to >= n1 + n2) continue; assert(es[id].c > 0); if(es[id].f > 0) continue; res[k].push_back(es[id].id); } } } void solve() { int cnt = *min_element(pw, pw + n1 + n2); int s = n1 + n2; int t = s + 1; fore(i, 0, n1) add_edge(s, i, pw[i] - cnt, -1); fore(i, n1, n1 + n2) add_edge(i, t, pw[i] - cnt, -1); int mf = 0, mn = cnt; while(mn >= 0) { mf += dinic(s, t, n1 + n2 + 2); getCert(mn); if(mn > 0) { for (int id : g[s]) { assert(es[id].id < 0); assert((id & 1) == 0); es[id].c++; } for (int id : g[t]) { assert(es[id].id < 0); assert(es[id].c == 0); es[id ^ 1].c++; } } mn--; } fore(i, 0, cnt + 1) { printf("%d ", sz(res[i])); for(int id : res[i]) printf("%d ", id + 1); puts(""); } } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif if(read()) { solve(); } return 0; }
977
A
Wrong Subtraction
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: - if the last digit of the number is non-zero, she decreases the number by one; - if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions. It is guaranteed that the result will be positive integer number.
In this problem you just need to simulate the process described in the statement (i.e. $k$ times repeat the following operation: if $n \% 10 = 0$ then $n := n / 10$ else $n := n - 1$) and print the result.
[ "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 n, k; cin >> n >> k; for (int i = 0; i < k; ++i) { if (n % 10 == 0) n /= 10; else n--; } cout << n << endl; return 0; }
977
B
Two-gram
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams. You are given a string $s$ consisting of $n$ capital Latin letters. Your task is to find \textbf{any} two-gram contained in the given string \textbf{as a substring} (i.e. two consecutive characters of the string) maximal number of times. For example, for string $s$ = "BBAABBBA" the answer is two-gram "BB", which contained in $s$ three times. In other words, find any most frequent two-gram. Note that occurrences of the two-gram can overlap with each other.
There are at least two different approaches to this problem: You can iterate over all substrings of $s$ of length $2$ and calculate for each of them the number of its occurrences in $s$ (and try to update the result with the current substring). Also you can iterate over all two-grams in the alphabet and do the same as in the aforementioned solution.
[ "implementation", "strings" ]
900
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; cin >> n; string s; cin >> s; int res = 0; string ans; for (int i = 0; i < n - 1; ++i) { int cur = 0; for (int j = 0; j < n - 1; ++j) if (s[j] == s[i] && s[j + 1] == s[i + 1]) ++cur; if (res < cur) { res = cur; ans = string(1, s[i]) + string(1, s[i + 1]); } } cout << ans << endl; return 0; }
977
C
Less or Equal
You are given a sequence of integers of length $n$ and integer number $k$. You should print \textbf{any integer} number $x$ in the range of $[1; 10^9]$ (i.e. $1 \le x \le 10^9$) such that exactly $k$ elements of given sequence are less than or equal to $x$. Note that the sequence can contain equal elements. If there is no such $x$, print "-1" (without quotes).
In this problem you can do the following thing: firstly, let's sort our array. Let $ans$ will be the answer. Then you have two cases: if $k = 0$ then $ans := a_0 - 1$ otherwise $ans := a_{k - 1}$ (for 0-indexed array). Then you need to calculate the number of the elements of the array $a$ that are less than or equal to $ans$. Let it be $cnt$. Then if $ans < 1$ or $cnt \ne k$ then print "-1" otherwise print $ans$.
[ "sortings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; scanf("%d %d", &n, &k); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); sort(a.begin(), a.end()); int ans; if (k == 0) { ans = a[0] - 1; } else { ans = a[k - 1]; } int cnt = 0; for (int i = 0; i < n; ++i) if (a[i] <= ans) ++cnt; if (cnt != k || !(1 <= ans && ans <= 1000 * 1000 * 1000)) { puts("-1"); return 0; } printf("%d\n", ans); return 0; }
977
D
Divide by three, multiply by two
Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds: - divide the number $x$ by $3$ ($x$ must be divisible by $3$); - multiply the number $x$ by $2$. After each operation, Polycarp writes down the result on the board and replaces $x$ by the result. So there will be $n$ numbers on the board after all. You are given a sequence of length $n$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board. Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number. It is guaranteed that the answer exists.
Let $deg_3(x)$ be the maximum integer $y$ such that $3^y | x$ ($x$ is divisible by $3^y$). Our problem is to rearrange the given array in such a way that (easy to see it if we look at our operations) if it looks like $a_{i_1}, a_{i_2}, \dots, a_{i_n}$, then for each $k \in [1..n - 1]$ the next inequality will be satisfied: $deg_3(a_{i_k}) \ge deg_3(a_{i_k + 1})$. And if $deg_3(a_{i_k}) = deg_3(a_{i_k + 1})$ then numbers must be placed in increasing order (because of our operations). So we can store an array of pairs $ans$, when $ans_i = (x_i, y_i)$, $x_i = -deg_3(a_i)$, $y_i = a_i$. Then if we sort it in lexicographical order we can just print the second elements of the sorted array $ans$.
[ "dfs and similar", "math", "sortings" ]
1,400
#include <bits/stdc++.h> using namespace std; typedef long long LL; int count3(LL x){ int ret=0; while(x % 3 == 0){ ret++; x /= 3; } return ret; } int n; vector<pair<int,LL>> v; int main(){ cin>>n; v.resize(n); for(int i=0; i<n; i++){ cin>>v[i].second; v[i].first=-count3(v[i].second); } sort(v.begin(), v.end()); for(int i=0; i<n; i++) printf("%lld%c", v[i].second, " \n"[i + 1 == n]); }
977
E
Cyclic Components
You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles. Here are some definitions of graph theory. An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices. Two vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$. A connected component is a cycle if and only if its vertices can be reordered in such a way that: - the first vertex is connected with the second vertex by an edge, - the second vertex is connected with the third vertex by an edge, - ... - the last vertex is connected with the first vertex by an edge, - all the described edges of a cycle are distinct. A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices. \begin{center} {\small There are $6$ connected components, $2$ of them are cycles: $[7, 10, 16]$ and $[5, 11, 9, 15]$.} \end{center}
Let's solve this problem for each connected component of the given graph separately. It is easy to see that the connected component is a cycle iff the degree of each its vertex equals to $2$. So the solution is to count the number of components such that every vertex in the component has degree $2$. The connected components of the graph can be easily found by simple dfs or bfs.
[ "dfs and similar", "dsu", "graphs" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 200 * 1000 + 11; int n, m; int deg[N]; bool used[N]; vector<int> comp; vector<int> g[N]; void dfs(int v) { used[v] = true; comp.push_back(v); for (auto to : g[v]) if (!used[to]) dfs(to); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif scanf("%d %d", &n, &m); for (int i = 0; i < m; ++i) { int x, y; scanf("%d %d", &x, &y); --x, --y; g[x].push_back(y); g[y].push_back(x); ++deg[x]; ++deg[y]; } int ans = 0; for (int i = 0; i < n; ++i) { if (!used[i]) { comp.clear(); dfs(i); bool ok = true; for (auto v : comp) ok &= deg[v] == 2; if (ok) ++ans; } } printf("%d\n", ans); return 0; }
977
F
Consecutive Subsequence
You are given an integer array of length $n$. You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to $[x, x + 1, \dots, x + k - 1]$ for some value $x$ and length $k$. Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array $[5, 3, 1, 2, 4]$ the following arrays are subsequences: $[3]$, $[5, 3, 1, 2, 4]$, $[5, 1, 4]$, but the array $[1, 3]$ is not.
Let $dp[x]$ be the answer for our problem if the last element of our subsequence equals to $x$. Then we have an easy solution: let's store $dp$ as a "std::map" (C++) or "HashMap" (Java). Initially for each $i \in [1..n]$ $dp[a_i] = 0$. Then let's iterate over all $a_i$ in order of input and try to update $dp[a_i]$ with a $dp[a_i - 1] + 1$ ($dp[a_i] = max(dp[a_i], dp[a_i - 1] + 1)$). Then the maximum element of $dp$ will be our answer. Let it be $ans$. Then let's find any $a_i$ such that $dp[a_i] = ans$. Let it be $lst$. Then for restoring the answer we need to iterate over all elements of our array in reverse order and if the current element $a_k = lst$ then push $k$ to the array of positions of our subsequence and make $lst := lst - 1$.
[ "dp" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); map<int, int> dp; int ans = 0; int lst = 0; for (int i = 0; i < n; ++i) { int x = a[i]; dp[x] = dp[x - 1] + 1; if (ans < dp[x]) { ans = dp[x]; lst = x; } } vector<int> res; for (int i = n - 1; i >= 0; --i) { if (a[i] == lst) { res.push_back(i); --lst; } } reverse(res.begin(), res.end()); printf("%d\n", ans); for (auto it : res) printf("%d ", it + 1); puts(""); return 0; }
978
A
Remove Duplicates
Petya has an array $a$ consisting of $n$ integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
We will store integers which we already met in a set $exist$. Let's iterate through the given array from the right to the left. Let the current element is equal to $x$. So, if $x$ does not contain in $exist$ we add $x$ in a vector-answer $ans$ and add $x$ in $exist$. After we considered all elements the answer sequence contains in the vector $ans$ in reversed order. So we should reverse the vector $ans$ and simply print all its elements.
[ "implementation" ]
800
null
978
B
File Name
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed. Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx". You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".
Let's iterate through the given string from the left to the right. In a variable $cnt$ we will store the number of letters "x" which were before the current letter in a row. If the current letter does not equal to "x" we should make $cnt = 0$. In the other case, the current letter equals to "x". If $cnt < 2$, we should increase $cnt$ by one. In the other case, we should add one to the answer because the current letter should be removed.
[ "greedy", "strings" ]
800
null
978
C
Letters
There are $n$ dormitories in Berland State University, they are numbered with integers from $1$ to $n$. Each dormitory consists of rooms, there are $a_i$ rooms in $i$-th dormitory. The rooms in $i$-th dormitory are numbered from $1$ to $a_i$. A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $n$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $1$ to $a_1 + a_2 + \dots + a_n$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on. For example, in case $n=2$, $a_1=3$ and $a_2=5$ an envelope can have any integer from $1$ to $8$ written on it. If the number $7$ is written on an envelope, it means that the letter should be delivered to the room number $4$ of the second dormitory. For each of $m$ letters by the room number among all $n$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.
We should use that the letter queries are given in increasing order of room numbers. We will store in a variable $sum$ the number of rooms in already considered dormitories (this variable should have 64-bit type) and in a variable $idx$ we will store the minimum number of dormitory where the room from the current letter possibly is. Initially, $sum = 0$ and $idx = 1$. We will iterate through the letters. Let the current letter should be delivered to the room $x$. While $sum + a_{idx} < x$, we increase $sum$ by $a_{idx}$ and increase $idx$ by one. So, we got the dormitory number where room $x$ is. It only remains to print two integers: $idx$ (the dormitory number) and $(x - sum)$ (the room number in this dormitory).
[ "binary search", "implementation", "two pointers" ]
1,000
null
978
D
Almost Arithmetic Progression
Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3, 9]$ and $[2, 3, 1]$ are not. It follows from the definition that any sequence of length one or two is an arithmetic progression. Polycarp found some sequence of positive integers $[b_1, b_2, \dots, b_n]$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $1$, an element can be increased by $1$, an element can be left unchanged. Determine a minimum possible number of elements in $b$ which can be changed (by exactly one), so that the sequence $b$ becomes an arithmetic progression, or report that it is impossible. It is possible that the resulting sequence contains element equals $0$.
If $n \le 2$ we can print $0$, because each such sequence is an arithmetic progression. Note, that an arithmetic progression is uniquely determined by the first two terms. So we should brute $d_1$ from $-1$ to $1$ - the change of the first element of the given sequence, and $d_2$ from $-1$ to $1$ - the change of the second element of the given sequence. Then $a_1 = b_1 + d_1$ and $a_2 = b_2 + d_2$. Also we will store $cnt$ - the number of changed elements in the sequence. Initially $cnt = |d_1| + |d_2|$. Now we need to iterate through the sequence from the third element to $n$-th. Let current element in the position $i$. It should be equals to $a_i = a_1 + (i - 1) \cdot (a_2 - a_1)$. If $|a_i - b_i| > 1$, then such arithmetic progression is unreachable. Else, if $a_i \ne b_i$ we should increase $cnt$ on one. After we considered all elements we should update the answer with the value of $cnt$, if for all $i$ it was true that $|a_i - b_i| \le 1$.
[ "brute force", "implementation", "math" ]
1,500
null
978
E
Bus Video System
The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops. If $x$ is the number of passengers in a bus just before the current bus stop and $y$ is the number of passengers in the bus just after current bus stop, the system records the number $y-x$. So the system records show how number of passengers changed. The test run was made for single bus and $n$ bus stops. Thus, the system recorded the sequence of integers $a_1, a_2, \dots, a_n$ (exactly one number for each bus stop), where $a_i$ is the record for the bus stop $i$. The bus stops are numbered from $1$ to $n$ in chronological order. Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $w$ (that is, at any time in the bus there should be from $0$ to $w$ passengers inclusive).
Firstly we should find the minimum and maximum numbers of passengers, which could be in a bus if initially it was empty. Let $b = 0$. We should iterate through the bus stops. For the $i$-th bus stop, we add $a_i$ to $b$ and update with a value of $b$ the minimum number of passengers $minB$ and the maximum number of passengers $maxB$. If $maxB > w$, it is an invalid case and we should print 0, because the maximum number of passengers should be less or equal to $w$. Let $lf$ is a minimum possible number of passengers in the bus before the first stop and $rg$ - maximum possible. If $minB < 0$ then in the bus initially were at least $-minB$ passengers. Because we should make $lf = -minB$, else, $lf = 0$. If $maxB \le 0$, then $rg = w$, else, $rg = w - maxB$. After that we should compare $lf$ and $rg$. If $lf > rg$ - print 0. In the other case, print $rg - lf + 1$, because each of those values is correct.
[ "combinatorics", "math" ]
1,400
null
978
F
Mentors
In BerSoft $n$ programmers work, the programmer $i$ is characterized by a skill $r_i$. A programmer $a$ can be a mentor of a programmer $b$ if and only if the skill of the programmer $a$ is strictly greater than the skill of the programmer $b$ $(r_a > r_b)$ and programmers $a$ and $b$ are not in a quarrel. You are given the skills of each programmers and a list of $k$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $i$, find the number of programmers, for which the programmer $i$ can be a mentor.
Firstly we should sort all programmers in non-decreasing order of their skills. Also we need to store initially numbers of the programmers (we can user array of pairs - skill and initial number of the programmer). We will iterate through the programmers from the left to the right. The current programmer can be a mentor of all programmers to the left of him after sort and with who he are not in a quarrel. Let the number of programmers to the left is $x$. Subtract from $x$ the number of already considered programmers, who skill equals to the skill of the current programmer (it can be done, for example, with help of $map$). Also lets brute all programmers with who the current programmer in a quarrel (we can initially save for each programmer the vector of programmers with who he in a quarell; by analogy with the stoe of graphs) and if the skill of the current programmer more than the skill of a programmers, with which he in a quarrel, we should decrease $x$ on one, because this programmer is to the left of the current after sort and has been counted in $x$. We should store by a number of the current programmer the value $x$ as answer for him.
[ "binary search", "data structures", "implementation" ]
1,500
null
978
G
Petya's Exams
Petya studies at university. The current academic year finishes with $n$ special days. Petya needs to pass $m$ exams in those special days. The special days in this problem are numbered from $1$ to $n$. There are three values about each exam: - $s_i$ — the day, when questions for the $i$-th exam will be published, - $d_i$ — the day of the $i$-th exam ($s_i < d_i$), - $c_i$ — number of days Petya needs to prepare for the $i$-th exam. For the $i$-th exam Petya should prepare in days between $s_i$ and $d_i-1$, inclusive. There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the $i$-th exam in day $j$, then $s_i \le j < d_i$. It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days. Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
If in the current day there is no exam, we should prepare for an exam, for which questions already given, for which we prepare less than needed and which will be before other remaining exams. For this we will use array $cnt$, where $cnt_i$ equals to the number of days, which we already prepared for exam $i$. Initially, array $cnt$ consists of zeroes. Let's iterate through the days. Suppose exam $x$ is in the current day. If $cnt_x < d_x$, we did not have time to prepare for it and we should print -1. In the other case, in this day we will pass the exam $x$. In the other case, let iterate through all exams and choose exam $x$, for which we need still to prepare (i. e. $cnt_x < d_x$), for which already given the questions, and which will be before other remaining exams. If there is no such exam, we should relax in this day, else, in this day we should prepare for exam $x$. Also, we should increase $cnt_x$ by one.
[ "greedy", "implementation", "sortings" ]
1,700
null
979
A
Pizza, Pizza, Pizza!!!
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro. She has ordered a very big round pizza, in order to serve her many friends. Exactly $n$ of Shiro's friends are here. That's why she has to divide the pizza into $n + 1$ slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over. Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator. As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
If $n = 0$, the answer is obviously $0$. If $n + 1$ is even, we can make $\textstyle{\frac{n+1}{2}}$ diametric cuts. Otherwise, the only way is to make $n + 1$ cuts. Time complexity: $O(1)$.
[ "math" ]
1,000
#include <stdio.h> using namespace std; long long n; int main() { scanf("%I64d", &n); n++; if (n == 1) printf("0"); else if (n % 2 == 0) printf("%I64d", n / 2); else printf("%I64d", n); return 0; }
979
B
Treasure Hunt
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her. The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons. A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $7$ because its subribbon a appears $7$ times, and the ribbon abcdabc has the beauty of $2$ because its subribbon abc appears twice. The rules are simple. The game will have $n$ turns. Every turn, each of the cats must change strictly \textbf{one} color (at one position) in his/her ribbon to an arbitrary color which is \textbf{different} from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $n$ turns wins the treasure. Could you find out who is going to be the winner if they all play optimally?
We all knew that the substrings with length $1$ appear at most in the string. So, to make a string as beautiful as possible, we will choose the letter that firstly appears at most in the string and replace all the other letters with the chosen letter. There is some cases. If $n$ is less than or equal to the number of remaining letters, just add $n$ to the beauty. If $n$ is even after replacing all letters with the chosen, we can choose an arbitrary letter, replace it with some other letter, return it back and repeat the work till $n$ reach $0$. Otherwise, we will not replace all the other letters. Instead, we will replace the letters until there is $1$ letter left (now $n$ is even) then replace that one with another letter different from our chosen letter. After that, replace that letter with our chosen letter. Now $n$ is even again, we repeat the work discussed above. In conclusion, let's call our string $s$, our chosen letter $a$ and its number of occurrences in the string $f_{a}$, then our answer is $min(f_{a} + n, |s|)$. Be careful with $n = 1$. Time complexity: $O(\Sigma\backslash|S|)$, where $\textstyle\sum|S|$ is the total length of the three strings.
[ "greedy" ]
1,800
#include <bits/stdc++.h> using namespace std; int a[256], b[256], c[256], n, ma, mb, mc; string p, q, r; int main() { cin >> n >> p >> q >> r; for (char x: p) ma = max(ma, ++a[x]); for (char x: q) mb = max(mb, ++b[x]); for (char x: r) mc = max(mc, ++c[x]); if (n == 1 && ma == (int)p.length()) p.pop_back(); if (n == 1 && mb == (int)q.length()) q.pop_back(); if (n == 1 && mc == (int)r.length()) r.pop_back(); ma = min(ma + n, (int)p.length()); mb = min(mb + n, (int)q.length()); mc = min(mc + n, (int)r.length()); if (ma > mb && ma > mc) { puts("Kuro"); return 0; } if (mb > ma && mb > mc) { puts("Shiro"); return 0; } if (mc > ma && mc > mb) { puts("Katie"); return 0; } puts("Draw"); return 0; }
979
C
Kuro and Walking Route
Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $(u, v)$ ($u \neq v$) and walk from $u$ using the shortest path to $v$ (note that $(u, v)$ is considered to be different from $(v, u)$). Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $x$) and Beetopia (denoted with the index $y$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $(u, v)$ if on the path from $u$ to $v$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him. Kuro wants to know how many pair of city $(u, v)$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
We can consider the city as a graph, in which every town is a vertex and every road connecting two towns is an edge. Since $m$ < $n$, we can deduce that this graph is a tree. Now, instead of finding the number of pairs that Kuro can choose, we can find the number of pairs that Kuro cannot choose. In other words, we must find the number of pairs of vertices $(u, v)$, in which the shortest path from $u$ to $v$ passes through $x$ and then through $y$. But how can we do this? If we take vertex $y$ as the root of the tree, we can see that every pair of vertices that Kuro cannot choose begins from any node within the subtree of node $x$, and finishes at any node but within the subtree of node $z$, which $z$ is a direct child of $y$ lying on the shortest path from $x$ to $y$. In total, the number of pairs of vertices that we are looking for is equal of $n \cdot (n - 1) - s[x] \cdot (s[y] - s[z])$, which $s[i]$ denotes the size of the subtree of node $i$. We can implement this using simple DFS. Time complexity: $O(n)$.
[ "dfs and similar", "trees" ]
1,600
#include <iostream> #include <cstdio> #include <vector> using namespace std; const int MAXN = 3e5; int n, m, u, v, x, y, sub_size[MAXN + 5]; bool vis[MAXN + 5], chk_sub[MAXN + 5]; vector<int> adj[MAXN + 5]; int DFS(int u) { vis[u] = true; sub_size[u] = 1; if (u == x) chk_sub[u] = true; else chk_sub[u] = false; for (int v: adj[u]) if (!vis[v]) { sub_size[u] += DFS(v); chk_sub[u] |= chk_sub[v]; } return sub_size[u]; } int main() { scanf("%d%d%d", &n, &x, &y); m = n - 1; while (m--) { scanf("%d%d", &u, &v); adj[u].push_back(v); adj[v].push_back(u); } DFS(y); long long fin; for (int v: adj[y]) if (chk_sub[v]) { fin = sub_size[y] - sub_size[v]; break; } printf("%I64d", 1LL * n * (n - 1) - fin * sub_size[x]); return 0; }
979
D
Kuro and GCD and XOR and SUM
Kuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day. Sadly, he's going on a vacation for a day, and he isn't able to continue his solving streak on his own. As Katie is a reliable person, Kuro kindly asked her to come to his house on this day to play the game for him. Initally, there is an empty array $a$. The game consists of $q$ tasks of two types. The first type asks Katie to add a number $u_i$ to $a$. The second type asks Katie to find a number $v$ existing in $a$ such that $k_i \mid GCD(x_i, v)$, $x_i + v \leq s_i$, and $x_i \oplus v$ is maximized, where $\oplus$ denotes the bitwise XOR operation, $GCD(c, d)$ denotes the greatest common divisor of integers $c$ and $d$, and $y \mid x$ means $x$ is divisible by $y$, or report -1 if no such numbers are found. Since you are a programmer, Katie needs you to automatically and accurately perform the tasks in the game to satisfy her dear friend Kuro. Let's help her!
We first look at the condition $k_{i}\mid G C D(x_{i},v)$. This condition holds iff both $x_{i}$ and $v$ are divisible by $k_{i}$. Therefore, if $k_{i}\uparrow x_{i}$, we return -1 immediately, else we only consider numbers in $a$ that are divisible by $k_{i}$. Finding the maximum XOR of $x_{i}$ with $v$ in the array $a$ reminds us of a classic problem, where the data structure trie is used to descend from the higher bit positions to the lower bit positions. But since we only consider $v$ such that $k_{i}\mid v$ and $x_{i} + v \le s_{i}$, we build $10^{5}$ tries, where the $i^{th}$ trie holds information of numbers in $a$ that are divisible by $i$, and we only descend to a branch in the trie if the branch is not empty and the minimum value in the branch is $ \le s_{i} - x_{i}$. Adding a number into $a$ is trivial by now: we update every $u^{th}$ trie where $u$ divides the number we need to add into the array. Notice that we only add a number if the number doesn't exist in the array yet. Time complexity: $O(MAXlog(MAX) + qlog(MAX)^{2})$.
[ "binary search", "bitmasks", "brute force", "data structures", "dp", "dsu", "greedy", "math", "number theory", "strings", "trees" ]
2,200
#include <iostream> #include <cstdio> #include <vector> using namespace std; const int MAX = 1E5 + 5; struct SNode { int mi; SNode *bit[2]; SNode() { mi = MAX; bit[0] = bit[1] = nullptr; } } *rt[MAX]; vector<int> di[MAX]; int q, t, u, k, x, s; bool chk[MAX]; void init() { for (int i = 1; i < MAX; i++) { for (int j = i; j < MAX; j += i) di[j].push_back(i); rt[i] = new SNode(); } } void add(int k, int u) { SNode *cur = rt[k]; cur->mi = min(cur->mi, u); for (int i = 18; i >= 0; i--) { if (cur->bit[u >> i & 1] == nullptr) cur->bit[u >> i & 1] = new SNode(); cur = cur->bit[u >> i & 1]; cur->mi = min(cur->mi, u); } } int que(int x, int k, int s) { SNode *cur = rt[k]; if (x % k != 0 || cur->mi + x > s) return -1; int ret = 0; for (int i = 18; i >= 0; i--) { int bi = x >> i & 1; if (cur->bit[bi ^ 1] != nullptr && cur->bit[bi ^ 1]->mi + x <= s) { ret += ((bi ^ 1) << i); cur = cur->bit[bi ^ 1]; } else { ret += (bi << i); cur = cur->bit[bi]; } } return ret; } int main() { init(); scanf("%d", &q); while (q--) { scanf("%d", &t); if (t == 1) { scanf("%d", &u); if (!chk[u]) { chk[u] = true; for (int k : di[u]) add(k, u); } } else { scanf("%d%d%d", &x, &k, &s); printf("%d\n", que(x, k, s)); } } return 0; }
979
E
Kuro and Topological Parity
Kuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games. Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot of arrows (you can assume that the number of arrows is infinite). Immediately, Katie came up with the game called Topological Parity. The paper is divided into $n$ pieces enumerated from $1$ to $n$. Shiro has painted some pieces with some color. Specifically, the $i$-th piece has color $c_{i}$ where $c_{i} = 0$ defines black color, $c_{i} = 1$ defines white color and $c_{i} = -1$ means that the piece hasn't been colored yet. The rules of the game is simple. Players must put some arrows between some pairs of different pieces in such a way that for each arrow, the number in the piece it starts from is less than the number of the piece it ends at. Also, two different pieces can only be connected by \textbf{at most} one arrow. After that the players must choose the color ($0$ or $1$) for each of the unpainted pieces. The score of a valid way of putting the arrows and coloring pieces is defined as the number of paths of pieces of alternating colors. For example, $[1 \to 0 \to 1 \to 0]$, $[0 \to 1 \to 0 \to 1]$, $[1]$, $[0]$ are valid paths and will be counted. You can only travel from piece $x$ to piece $y$ if and only if there is an arrow from $x$ to $y$. But Kuro is not fun yet. He loves parity. Let's call his favorite parity $p$ where $p = 0$ stands for "even" and $p = 1$ stands for "odd". He wants to put the arrows and choose colors in such a way that the score has the parity of $p$. It seems like there will be so many ways which satisfy Kuro. He wants to count the number of them but this could be a very large number. Let's help him with his problem, but print it modulo $10^{9} + 7$.
The problem asks us to find the number of different simple directed acyclic graphs with $1 \rightarrow n$ forming its topological order to ensure the parity of the number of alternating paths to be equal to $p$. We will solve this problem using the dynamic programming approach. Let's define even-white as the number of different nodes $u$ colored in white that has an even number of alternating paths that end in $u$. In the same fashion, let's define odd-white as the number of different nodes $u$ colored in white that has an odd number of alternating paths that end in $u$, even-black - the number of different nodes $u$ colored in black that has an even number of alternating paths that end in $u$, and odd-black - the number of different nodes $u$ colored in black that has an odd number of alternating paths that end in $u$. Let's also define $dp[i][ew][ow][eb]$ as the number of different graphs following the requirements that can be built using the first $i$ nodes, with $ew$ even-white nodes, $ow$ odd-white nodes and $eb$ even-black nodes (the number of odd-black nodes $ob = i - ew - ow - eb$). We will figure out how to calculate such value. For the sake of simplicity, let's consider the current node - the ${i}^{th}$ node to be a white node. We can notice a few things: If none of the previous $i - 1$ nodes connects to the current node, the current node becomes an odd-white node (the only alternating path that ends the current node is the node itself). If none of the previous $i - 1$ nodes connects to the current node, the current node becomes an odd-white node (the only alternating path that ends the current node is the node itself). How the previous white nodes connect to the current node does not matter. There are $2^{ow + ew - 1}$ ways to add edges between the previous white nodes and the current node. How the previous white nodes connect to the current node does not matter. There are $2^{ow + ew - 1}$ ways to add edges between the previous white nodes and the current node. How the previous even-black nodes connect to the current node does not matter, as it does not change the state of the current white node (i.e. odd-white to even-white or even-white to odd-white). There are $2^{eb}$ ways to add edges between the previous even-black nodes and the current node. How the previous even-black nodes connect to the current node does not matter, as it does not change the state of the current white node (i.e. odd-white to even-white or even-white to odd-white). There are $2^{eb}$ ways to add edges between the previous even-black nodes and the current node. If there are an odd number of previous odd-black nodes that have edges to the current node, the current node becomes an even-white node. There are $\sum_{\begin{array}{l}{\scriptstyle\in\;\bigcup_{i=1}^{0,b}}\\ {\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad}}\\ {\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad$ ways to do this. If there are an odd number of previous odd-black nodes that have edges to the current node, the current node becomes an even-white node. There are $\sum_{\begin{array}{l}{\scriptstyle\in\;\bigcup_{i=1}^{0,b}}\\ {\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad}}\\ {\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad$ ways to do this. If there are an even number of previous odd-black nodes that have edges to the current node, the current node becomes an odd-white node. There are $\sum_{k=0}^{\left\lfloor{\frac{\alpha\beta}{2\delta}}\right\rfloor}\;\left({\frac{\partial\beta}{\delta k}}\right)$ ways to do this. If there are an even number of previous odd-black nodes that have edges to the current node, the current node becomes an odd-white node. There are $\sum_{k=0}^{\left\lfloor{\frac{\alpha\beta}{2\delta}}\right\rfloor}\;\left({\frac{\partial\beta}{\delta k}}\right)$ ways to do this. In conclusion, we can figure out that: $\begin{array}{c}{{d p[i][e w][o w][e b]=2^{o w+e w+e b-1}\cdot\left(d p[i-1][e w-1][e w][e b]\cdot\sum_{k=0}^{\lfloor\frac{g b}{2}\rfloor}\left({\frac{g b}{2k+1}}\right)+}}\\ {{d p[i-1][e w][o w-1][e w][o w-1][e b]\cdot\sum_{k=0}^{\lfloor\frac{g b}{2k}\rfloor}\left({\frac{g b}{2k}}\right)}}\end{array}$ It is worth mentioning that we can use the same analogy to process when the current node is black. In total, we process through $n^{4}$ states, with an $O(n)$ iteration for each stage, so the time complexity is $O(n^{5})$. However, with precomputation of $\sum_{\begin{array}{l}{\scriptstyle\in\;\bigcup_{i=1}^{0,b}}\\ {\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad}\end{array}\quad\quad$ and $\sum_{k=0}^{\left\lfloor{\frac{\left\lfloor{\frac{\omega}{k}}\right\rfloor}{k}}\setminus\left({\frac{\partial}{\partial k}}\right)}$ for every value of $ob$, we can optimize the time complexity to $O(n^{4})$. Time complexity: $O(n^{4})$.
[ "dp" ]
2,400
#include <iostream> using namespace std; const int N = 55, MOD = 1E9 + 7; int n, p, c[N]; long long ans = 0, pw[N], fct[N], inv[N], od[N], ev[N], f[N][N][N][N]; long long power(int u, int p) { if (p == 0) return 1; long long ret = power(u, p >> 1); (ret *= ret) %= MOD; if (p & 1) (ret *= u) %= MOD; return ret; } long long C(int n, int k) { return fct[n] * inv[k] % MOD * inv[n - k] % MOD; } void init() { f[0][0][0][0] = 1; pw[0] = 1; fct[0] = 1; for (int i = 1; i < N; i++) { pw[i] = pw[i - 1] * 2 % MOD; fct[i] = fct[i - 1] * i % MOD; } inv[N - 1] = power(fct[N - 1], MOD - 2); for (int i = N - 2; i >= 0; i--) inv[i] = inv[i + 1] * (i + 1) % MOD; for (int i = 0; i < N; i++) { for (int j = 0; j <= i; j += 2) (ev[i] += C(i, j)) %= MOD; for (int j = 1; j <= i; j += 2) (od[i] += C(i, j)) %= MOD; } } void find_ans(int ob, int eb, int ow, int ew, int col, long long &ret) { // current node is even-white if (col != 0 && ew != 0) (ret += f[ob][eb][ow][ew - 1] * pw[ow + ew - 1 + eb] % MOD * od[ob] % MOD) %= MOD; // current node is odd-white if (col != 0 && ow != 0) (ret += f[ob][eb][ow - 1][ew] * pw[ow - 1 + ew + eb] % MOD * ev[ob] % MOD) %= MOD; // current node is even-black if (col != 1 && eb != 0) (ret += f[ob][eb - 1][ow][ew] * pw[ob + eb - 1 + ew] % MOD * od[ow] % MOD) %= MOD; // current node is odd-black if (col != 1 && ob != 0) (ret += f[ob - 1][eb][ow][ew] * pw[ob - 1 + eb + ew] % MOD * ev[ow] % MOD) %= MOD; } int main() { init(); scanf("%d%d", &n, &p); for (int i = 1; i <= n; i++) scanf("%d", c + i); for (int i = 1; i <= n; i++) for (int ob = 0; ob <= i; ob++) for (int eb = 0; ob + eb <= i; eb++) for (int ow = 0; ob + eb + ow <= i; ow++) { int ew = i - ob - eb - ow; find_ans(ob, eb, ow, ew, c[i], f[ob][eb][ow][ew]); if (i == n && ((ob + ow) & 1) == p) (ans += f[ob][eb][ow][ew]) %= MOD; } printf("%lld", ans); return 0; }
980
A
Links and Pearls
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts. Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them. Note that the final necklace should remain as one circular part of the same length as the initial necklace.
The problem can be viewed as the following: You have a cyclic array with the characters '-' and 'o', you want to rearrange the elements of the array such that the number of '-' characters after every 'o' character is the same. So we want to distribute the '-' characters over the 'o' characters so that all the 'o' characters have the same number of '-' characters after them. If we have $a$ of 'o' and $b$ of '-', then that can be done if and only if $b \bmod a = 0$. When $a = 0$, the answer is YES since the condition still holds.
[ "implementation", "math" ]
900
null
980
B
Marlin
The city of Fishtopia can be imagined as a grid of $4$ rows and an \textbf{odd} number of columns. It has two main villages; the first is located at the top-left cell $(1,1)$, people who stay there love fishing at the Tuna pond at the bottom-right cell $(4, n)$. The second village is located at $(4, 1)$ and its people love the Salmon pond at $(1, n)$. The mayor of Fishtopia wants to place $k$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells. A person can move from one cell to another if those cells are not occupied by hotels and share a side. Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?
Instead of looking at the second path from $(4, 1)$ to $(1, n)$, consider it as from $(1, n)$ to $(4, 1)$. Now when $k$ is even, we can do the following: start from (2,2), put a hotel in that cell and another hotel in (2,n-1), then a hotel in (2,3) and one in (2, n-2), and so on until either the second row is full (expect for the middle column) or the number of hotels is $k$, if you still need more hotels then just do the same for the third row. This works because going from $(1, 1)$ to $(4, n)$ is identical to going from $(1, n)$ to $(4, 1)$ since the constructed grid is symmetric. Now if $k = 2*(n-2)$ then just fill the the middle column (second and third row), and if $k$ is odd then just add a hotel in middle column.
[ "constructive algorithms" ]
1,600
null
980
C
Posterized
Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter. Their algorithm will be tested on an array of integers, where the $i$-th integer represents the color of the $i$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive). To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $k$, and each color should belong to exactly one group. Finally, the students will replace the color of each pixel in the array with that color’s assigned group key. To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $k$ to the right. To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.
First, it's obvious that for each group we should choose the color with minimum value as the group's key. Now since we want to find the lexicographically smallest array, we iterate from the leftmost number in the array and minimize it as much as possible without considering the numbers to its right. There are many ways to implement this, one of them is the following: Iterate from left to right, for each number $x$, if it is already assigned to a group then ignore it. Otherwise, check the colors less than $x$ in decreasing order until you find a color $y$ that is assigned. If we can extend the group of $y$ to include $x$ and the size won't be exceeding $k$, then we do extend it and assign all the colors between $y+1$ and $x$ to the key of $y$'s group. If the size will exceed $k$ or such $y$ was not found (set it to $-1$ in this case), we create a new group with key equals to $max(y+1,x-k+1)$ and assign all colors in the range to it. The complexity of this solution is $O(n + c)$, where $c$ is the size of the color range.
[ "games", "greedy" ]
1,700
null
980
D
Perfect Groups
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array $A$ of $n$ integers, and he needs to find the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$ for each integer $k$ between $1$ and $n$ (inclusive).
First let us examine perfect squares; a perfect square is a number $x$ that can be written as the product of an integer and itself $y*y$. This means that for each prime factor of the number $x$, the frequency of that factor must be even so it can be distributed evenly between each of the two $y$'s. This leads to the idea that for every two numbers $a$ and $b$ in a group, for a prime factor $p_{i}$, either both $a$ and $b$ have an even frequency of $p_{i}$, or they both have an odd frequency of it. So using that observation, for each number $x$ in the array we can discard all pairs of equal prime factors (keeping one copy of each factor with an odd frequency). For example, number $40$ has factors ${2, 2, 2, 5}$, so we can just ignore the first pair of $2's$ because they're redundant and transform it into ${2, 5}$, which is the number $10$. Now after replacing each number with the product of its odd factors, we can just count the number of distinct elements in each subarray as each element can be only grouped with its copies. This can be done by checking all possible subarrays and keeping a frequency array to count the number of distinct elements in it. - Elements need to be mapped to non-negative integers between $1$ and $n$ so we don't use a set to count them. - Need to be careful in case there's a zero in the subarray. Zeros can join any group, so unless the subarray contains only zeros, we can ignore them. Solution Complexity: $O(n\times sqrt(max a_i) + n^{2})$
[ "dp", "math", "number theory" ]
2,100
null
980
E
The Number Games
The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant. The nation has $n$ districts numbered from $1$ to $n$, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district $i$ is equal to $2^i$. This year, the president decided to reduce the costs. He wants to remove $k$ contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts. The president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants. Which contestants should the president remove?
As the final set of remaining districts need to be reachable from each other, this means that the resulting tree is a sub-graph of the original one. Now, looking at the number of fans in each district, district $i$ has $2^{i}$ fans. This means that if we had a choice of including a district $i$ in our solution and discarding all the districts with indices less than $i$ then it'd be better than discarding district $i$ and including all the others, as $2^{i} = 2^{i-1} + 2^{i-2} + ... + 2^{0} + 1$. This leads us to the following greedy solution: Let's try to find which districts to keep instead of which to discard, let's first root the tree at district $n$, as we can always keep it, and go through the remaining districts by the order of decreasing index. Now at each step, if we can include district $i$ into our solution by taking it and all of the nodes on the path connecting it to our current sub-graph, then we should surely do so, otherwise we can just ignore it and move on to the next district. This can be implemented by building a parent sparse-table and using Binary Lifting at each district $i$ to find the first of its ancestors that has been already included in our sub-graph. The distance to this ancestor represents the number of districts that need to be included in the games to have district $i$ included. So if we can still include that many districts in our sub-graph then we will traverse through the path and mark them as included. Solution Complexity: $O(nlogn)$
[ "data structures", "greedy", "trees" ]
2,200
null
980
F
Cactus to Tree
You are given a special connected undirected graph where each vertex belongs to at most one simple cycle. Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles). For each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance.
The following solution is implemented in 136 lines, but most of it is a simple BFS and two DFS functions for finding bridges and marking cycles, the main part of the solution is implemented in 38 lines. Please check the code after (or while?) reading if it is not clear. Note that if we run a BFS from a node $u$, the BFS spanning tree will represent the edges that we should keep to minimize the answer for node $u$. So we actually need to find the maximum length out of all shortest paths that starts at $u$ and end at every other node. We will first focus on finding the answer for each node on one cycle: For each node $u$ on the cycle, we can compute $L[u]$, the length of the longest shortest path that starts at node $u$ and uses only the edges that do not belong to the cycle. This can be done using BFS in $O(n+m)$ for one cycle. Using the computed values, we can find the final answer for all nodes on the cycle in $O(klogk)$, or $O(k)$, where $k$ is the number of nodes on the cycle. For a node $u$, we need to find a node $v$ on the cycle such that $L[v] + distance(u, v)$ is maximized, where $distance(u,v)$ is the length of the shortest path between $u$ and $v$ on the cycle. Therefore, the answer with regards to each node $u$ will be the maximum between $L[u]$ and $L[v] + distance(u, v)$, for each node $v$ in the same cycle as $u$. We can do this using a heap and prefix sums idea as follows: loop for $2k$ iterations over the cycle nodes, in the $i^{th}$ iteration ($0 \leq i < 2k$) add the value $L[cycle[i \bmod k]]+2k-i$ to the heap with the time it was added in ($time = 2k-i$, time is decreasing), that is, add the pair ($L[cycle[i \bmod k]]+2k-i, 2k-i$). Now at a given iteration $j$, pop from the heap all top values added at time greater than $2k-j+k/2$, as $distance(u,v)$ can't exceed $k/2$. Now assuming the top pair in the queue is ($x, y$), then $x-(2k-j)$ is a possible answer for this node. We need to do this again in counter-clockwise. Since we will visit each node four times, keep the maximum distance $Z_i$ found for each node $i$ in the cycle and the final answer for that node will be $max(L_i, Z_i)$. Now if we have the answer for one cycle, when we move using an edge ($a, b$) to another cycle (or node), we only need to know one value to be able to solve the next cycle, that value is the maximum between $Z_a$ and the length of the longest path that goes through bridges other than ($a, b$). This value is increased by $1$ when passed since we will move through the edge ($a, b$). Implementation: Marking the bridges will help in deciding if an edge will take us outside a cycle or not so we can compute $L_i$. Also removing the bridges will make it easy to find which nodes form each cycle. We can find any BFS spanning tree and use it to find the length of the longest path that starts at a node and uses a bridge first, note that this distance goes only down as the tree is rooted at the starting node, but the values $L_u$ for every $u$ in the first cycle will be correct so we can start with them.
[ "dp", "graphs", "trees" ]
2,900
"#include <stdio.h>\n#include <vector>\n#include <queue>\n#include <memory.h>\n#include <algorithm>\nusing namespace std;\ntypedef long long ll;\nconst int N = 500000;\nint n, m;\nint L[N], Z[N], maxLen[N];\nvector<vector<pair<int, int> > > g;\nbool isBridge[2 * N];\nint low[N], idx[N], dfs;\nbool vis[N];\nint parent[N];\nvoid markBridges(int u, int p) {\n\tlow[u] = idx[u] = ++dfs;\n\tfor (int i = 0; i < g[u].size(); ++i) {\n\t\tint v = g[u][i].first;\n\t\tif (idx[v] == 0) {\n\t\t\tmarkBridges(v, u);\n\t\t\tlow[u] = min(low[u], low[v]);\n\t\t\tif (low[v] > idx[u])\n\t\t\t\tisBridge[g[u][i].second] = true;\n\t\t}\n\t\telse if (v != p)\n\t\t\tlow[u] = min(low[u], idx[v]);\n\t}\n}\nvoid findASpanningTreeAndInitializeL(int startingNode) {\n\tqueue<int> q;\n\tvector<int> nodesByDepth;\n\tq.push(startingNode);\n\tmemset(vis, 0, sizeof(vis));\n\tvis[startingNode] = true;\n\tparent[startingNode] = -1;\n\twhile (!q.empty()) {\n\t\tint u = q.front();\n\t\tq.pop();\n\t\tnodesByDepth.push_back(u);\n\t\tfor (auto e : g[u]) {\n\t\t\tint v = e.first;\n\t\t\tif (vis[v])\n\t\t\t\tcontinue;\n\t\t\tvis[v] = true;\n\t\t\tparent[v] = u;\n\t\t\tq.push(v);\n\t\t}\n\t}\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tint u = nodesByDepth[i];\n\t\tfor (auto e : g[u]) {\n\t\t\tint v = e.first;\n\t\t\tif (parent[v] == u) {\n\t\t\t\tmaxLen[u] = max(maxLen[u], 1 + maxLen[v]);\n\t\t\t\tif (isBridge[e.second])\n\t\t\t\t\tL[u] = max(L[u], 1 + maxLen[v]);\n\t\t\t}\n\t\t}\n\t}\n}\nvector<vector<int> > cycles; // actually components after removing bridges, not cycles (as there can be a single node).\nint cycleIdx[N];\nvoid findCycles(int u) {\n\tvis[u] = true;\n\tcycles.back().push_back(u);\n\tcycleIdx[u] = cycles.size() - 1;\n\tfor (auto e : g[u])\n\t\tif (!isBridge[e.second] && !vis[e.first])\n\t\t\tfindCycles(e.first);\n}\nvoid solveCycles(int u, int p, int upValue) {\n\tL[u] = max(L[u], upValue);\n\tvector<int> &cycle = cycles[cycleIdx[u]];\n\tint k = cycle.size();\n\tfor (int it = 0; it < 2; ++it) { // two iterations, clockwise and counter clockwise\n\t\tpriority_queue<pair<int, int> > q;\n\t\tfor (int i = 0; i < 2 * k; ++i) {\n\t\t\tint d = 2 * k - i;\n\t\t\twhile (!q.empty() && q.top().second - d > k / 2)\n\t\t\t\tq.pop();\n\t\t\tif (!q.empty())\n\t\t\t\tZ[cycle[i%k]] = max(Z[cycle[i%k]], q.top().first - d);\n\t\t\tq.push({ L[cycle[i%k]] + d,d });\n\t\t}\n\t\treverse(cycle.begin(), cycle.end());\n\t}\n\tfor (auto u : cycle) {\n\t\tint firstMax = 0, secondMax = 0;\n\t\tfor (auto e : g[u])\n\t\t\tif (e.first != p && isBridge[e.second]) {\n\t\t\t\tint v = e.first;\n\t\t\t\tif (secondMax < 1 + maxLen[v]) {\n\t\t\t\t\tsecondMax = 1 + maxLen[v];\n\t\t\t\t\tif (firstMax < secondMax)\n\t\t\t\t\t\tswap(firstMax, secondMax);\n\t\t\t\t}\n\t\t\t}\n\t\tfor (auto e : g[u])\n\t\t\tif (e.first != p && isBridge[e.second]) {\n\t\t\t\tint v = e.first;\n\t\t\t\tint passValue = max(upValue, Z[u]);\n\t\t\t\tif (firstMax == 1 + maxLen[v])\n\t\t\t\t\tpassValue = max(passValue, secondMax);\n\t\t\t\telse\n\t\t\t\t\tpassValue = max(passValue, firstMax);\n\t\t\t\tsolveCycles(v, u, passValue + 1);\n\t\t\t}\n\t}\n}\nint main()\n{\n\tscanf(\"%d%d\", &n, &m);\n\tg.resize(n);\n\tfor (int i = 0, u, v; i < m; ++i) {\n\t\tscanf(\"%d%d\", &u, &v);\n\t\t--u; --v;\n\t\tg[u].push_back({ v,i });\n\t\tg[v].push_back({ u,i });\n\t}\n\tmarkBridges(0, -1);\n\tfor (int i = 0; i < n; ++i)\n\t\tif (!vis[i]) {\n\t\t\tcycles.push_back(vector<int>());\n\t\t\tfindCycles(i);\n\t\t}\n\tfindASpanningTreeAndInitializeL(0);\n\tsolveCycles(0, -1, 0);\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (i > 0)\n\t\t\tprintf(\" \");\n\t\tprintf(\"%d\", max(L[i], Z[i]));\n\t}\n\tprintf(\"\\n\");\n\treturn 0;\n}"
981
A
Antipalindrome
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring $s[l \ldots r]$ ($1 \leq l \leq r \leq |s|$) of a string $s = s_{1}s_{2} \ldots s_{|s|}$ is the string $s_{l}s_{l + 1} \ldots s_{r}$. Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $s$ is changed into its longest substring that is not a palindrome. If all the substrings of $s$ are palindromes, she skips the word at all. Some time ago Ann read the word $s$. What is the word she changed it into?
You can just check all substrings on palindromity in $O(n^3)$. Also you can note that if all characters in the string are same, then answer is $0$, else, if string is not a palindrome, answer is $n$, else you can delete last char and get answer $n-1$, so you can solve the task in $O(n)$.
[ "brute force", "implementation", "strings" ]
900
null
981
B
Businessmen Problems
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies. All elements are enumerated with integers. The ChemForces company has discovered $n$ distinct chemical elements with indices $a_1, a_2, \ldots, a_n$, and will get an income of $x_i$ Berland rubles if the $i$-th element from this list is in the set of this company. The TopChemist company discovered $m$ distinct chemical elements with indices $b_1, b_2, \ldots, b_m$, and it will get an income of $y_j$ Berland rubles for including the $j$-th element from this list to its set. In other words, the first company can present any subset of elements from $\{a_1, a_2, \ldots, a_n\}$ (possibly empty subset), the second company can present any subset of elements from $\{b_1, b_2, \ldots, b_m\}$ (possibly empty subset). There shouldn't be equal elements in the subsets. Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.
With $map$ data structure for each chemical element that presents in input find maximal cost that you can get, and then just sum up these costs
[ "sortings" ]
1,000
null
981
C
Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path. Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Let's prove that all paths in this decomposition have one intersection vertex. 1) Any pair of paths have exactly one intersecting vertex, because else there are common edge (so it is not a decomposition) or cycle (so graph is not a tree). 2) Let's assume that there are several intersection points. Let us have three paths $A$, $B$, $C$, and intersecting points are $P(AB), P(AC), P(BC)$. Then these intersecting points are pairwise different, but $P(AB) \to P(AC) \to P(BC)$ - cycle in the tree, so we get a contradiction. So we proved that for each triple of paths all intersection points are the same, $\to$ all paths in this decomposition have one intersecting vertex. So we proved that we can decompose the tree only if the tree looks like a vertex and several paths incoming from it. So you can choose the root in this tree - vertex with degree bigger than two (if there are no such vertex then the tree is bamboo and you can check that case separately or take any vertex as root). If there are several such vertices, when there is no decomposition. And then you can connect root with all leaves.
[ "implementation", "trees" ]
1,400
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <unordered_set>\n#include <iomanip>\n#include <bitset>\n#include <sstream>\n\nusing namespace std;\n\ntypedef long long ll;\n\nmt19937 rnd(228);\n\nconst int N = 1e5 + 1;\n\nvector <int> g[N];\n\nvector <int> leafs;\n\nvoid dfs(int v, int pr)\n{\n int deg = 0;\n for (int to : g[v])\n {\n if (to != pr)\n {\n deg++;\n dfs(to, v);\n }\n }\n if (deg == 0)\n {\n leafs.push_back(v);\n }\n}\n\nint main()\n{\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n;\n cin >> n;\n for (int i = 1; i < n; i++)\n {\n int a, b;\n cin >> a >> b;\n a--, b--;\n g[a].push_back(b);\n g[b].push_back(a);\n }\n int root = 0;\n int cnt = 0;\n for (int i = 0; i < n; i++)\n {\n if ((int) g[i].size() > 2)\n {\n cnt++;\n root = i;\n }\n }\n if (cnt > 1)\n {\n cout << \"No\\n\";\n }\n else\n {\n cout << \"Yes\\n\";\n dfs(root, -1);\n cout << (int) leafs.size() << '\\n';\n for (int i = 0; i < (int) leafs.size(); i++)\n {\n cout << root + 1 << ' ' << leafs[i] + 1 << '\\n';\n }\n }\n}"
981
D
Bookshelves
Mr Keks is a typical white-collar in Byteland. He has a bookshelf in his office with some books on it, each book has an integer positive price. Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office. He learned that in the new office he will have not a single bookshelf, but exactly $k$ bookshelves. He decided that the beauty of the $k$ shelves is the bitwise AND of the values of all the shelves. He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $k$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
Let's build answer from significant bit to least significant bit. We want to check, is there some partition in $k$ segments, such that all segment's sums have significant bit? We can check it with $dp_{n, k}$ - is there some partition of first $n$ elements on $k$ segments such that all segment's sums have significant bit? And then we will do the same with all other bits, we will try set $1$ in the bit, and then we want to check for fixed prefix of bits, is there some partition in $k$ segments, such that all prefixes with same length of all segment's sums are supermasks of current check mask (we will check that with the same dp, $dp_{n, k}$ - is there some partition of first $n$ elements on $k$ segments such that all prefixes of same length of all segment's sums are supermasks of current check mask?)
[ "bitmasks", "dp", "greedy" ]
1,900
"#include <cstdio>\n#include <cstring>\n\ntypedef long long int64;\nstatic const int MAXN = 52;\nstatic const int LOGA = 56;\n\nstatic int k, n;\nstatic int64 a[MAXN], s[MAXN];\n\nstatic bool feas[MAXN][MAXN];\n\ninline bool dp_check(int64 targ, int64 mask)\n{\n memset(feas, false, sizeof feas);\n feas[0][0] = true;\n for (int i = 1; i <= n; ++i) {\n for (int j = 0; j < i; ++j)\n if (((s[i] - s[j]) & mask & targ) == targ) {\n for (int k = 0; k < MAXN - 1; ++k)\n if (feas[j][k]) feas[i][k + 1] = true;\n }\n }\n return feas[n][k];\n}\n\nint main()\n{\n scanf(\"%d%d\", &n, &k);\n for (int i = 0; i < n; ++i) scanf(\"%lld\", &a[i]);\n s[0] = 0;\n for (int i = 0; i < n; ++i) s[i + 1] = s[i] + a[i];\n\n int64 ans = 0;\n for (int i = LOGA - 1; i >= 0; --i) {\n if (dp_check(ans | (1LL << i), ~((1LL << i) - 1))) ans |= (1LL << i);\n }\n printf(\"%lld\\n\", ans);\n\n return 0;\n}"
981
E
Addition on Segments
Grisha come to a contest and faced the following problem. You are given an array of size $n$, initially consisting of zeros. The elements of the array are enumerated from $1$ to $n$. You perform $q$ operations on the array. The $i$-th operation is described with three integers $l_i$, $r_i$ and $x_i$ ($1 \leq l_i \leq r_i \leq n$, $1 \leq x_i \leq n$) and means that you should add $x_i$ to each of the elements with indices $l_i, l_i + 1, \ldots, r_i$. After all operations you should find the maximum in the array. Grisha is clever, so he solved the problem quickly. However something went wrong inside his head and now he thinks of the following question: "consider we applied some subset of the operations to the array. What are the possible values of the maximum in the array?" Help Grisha, find all integers $y$ between $1$ and $n$ such that if you apply some subset (possibly empty) of the operations, then the maximum in the array becomes equal to $y$.
Suppose we know the index where the maximum is. Let's examine which requests we decided to take. Surely there is no need to take requests which doesn't contain the index of maximum. Because if you delete them, they will not impact maximum and nothing will change. This way we can see, that any possible answer is a sum of x's of some set of intersecting segments. We can go with a sweepline. Then when some request segment opens add new item to the knapsack. And delete one when it closes. The answer it the set of all possible sums we can obtain at some points. So we need to implement the following operations: 1) Add some number to the multiset. 2) Delete some number from the multiset. 3) Find all sums we can can obtain using the numbers from multiset. Let's store the following dp: $dp_x$ is the number of ways to get weight $x$. When we add new element $a$ we should go from the end of dp and recalculate it as $dp_i = dp_i + dp_{i-a}$, And when removing, doing the reverse transition: going from the beginning and relaxing as $dp_i = dp_i - dp_{i - a}$. And to find all achievable sums we should just print all $i$, such that $dp_i \neq 0$. However the exact values of $dp$ can be really large, so we can resort to a trick: let's cound all the dp values by some prime modulo, to avoid being hacked you should probably randomize it.
[ "bitmasks", "data structures", "divide and conquer", "dp" ]
2,200
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <iomanip>\n#include <bitset>\n\nusing namespace std;\n\ntypedef long long ll;\n\nmt19937 rnd(time(0));\n\nconst int N = 1e4 + 7;\nint MOD;\n\nbool prime(int x)\n{\n for (int i = 2; i * i <= x; i++)\n {\n if (x % i == 0)\n {\n return false;\n }\n }\n return (x != 1);\n}\n\nint dp[N];\nvector <pair <int, int> > e[N];\n\nvoid add(int x)\n{\n for (int i = N - 1 - x; i >= 0; i--)\n {\n dp[i + x] += dp[i];\n if (dp[i + x] >= MOD) dp[i + x] -= MOD;\n }\n}\n\nvoid del(int x)\n{\n for (int i = x; i < N; i++)\n {\n dp[i] -= dp[i - x];\n if (dp[i] < 0) dp[i] += MOD;\n }\n}\n\nint main()\n{\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n MOD = 5e8 + rnd() % (int) 5e8;\n while (!prime(MOD)) MOD--;\n int n, q;\n cin >> n >> q;\n dp[0] = 1;\n vector <bool> ans(n + 1);\n for (int i = 0; i < q; i++)\n {\n int l, r, x;\n cin >> l >> r >> x;\n l--, r--;\n e[l].push_back({x, 1});\n e[r + 1].push_back({x, -1});\n }\n for (int i = 0; i < n; i++)\n {\n for (auto c : e[i])\n {\n if (c.second == 1)\n {\n add(c.first);\n }\n else\n {\n del(c.first);\n }\n }\n for (int j = 1; j <= n; j++)\n {\n if (dp[j])\n {\n ans[j] = true;\n }\n }\n }\n vector <int> res;\n for (int i = 1; i <= n; i++)\n {\n if (ans[i])\n {\n res.push_back(i);\n }\n }\n cout << res.size() << '\\n';\n for (int x : res)\n {\n cout << x << ' ';\n }\n cout << '\\n';\n}"
981
F
Round Marriage
It's marriage season in Ringland! Ringland has a form of a circle's boundary of length $L$. There are $n$ bridegrooms and $n$ brides, and bridegrooms decided to marry brides. Of course, each bridegroom should choose exactly one bride, and each bride should be chosen by exactly one bridegroom. All objects in Ringland are located on the boundary of the circle, including the capital, bridegrooms' castles and brides' palaces. The castle of the $i$-th bridegroom is located at the distance $a_i$ from the capital in clockwise direction, and the palace of the $i$-th bride is located at the distance $b_i$ from the capital in clockwise direction. Let's define the inconvenience of a marriage the maximum distance that some bride should walk along the circle from her palace to her bridegroom's castle in the shortest direction (in clockwise or counter-clockwise direction). Help the bridegrooms of Ringland to choose brides in such a way that the inconvenience of the marriage is the smallest possible.
Key idea is that there there is a cut which is not crossed by anyoner (in other words, it is not profitable if brides will travel whole circle) So we can solve the problem in $O(n \cdot L)$ - fix the cut, and match $i$-th bridegrom (in increasing order) with $i$-th bride (if we will order brides in the traversal order starting from border), and relax answer with current inconvenience. Later we can note, that cuts not at brides are useless, so we can just choose cut from brides coordinates and get solution in $O(n^2)$. Later we can note, that we are just searching for optimal cyclical shift of brides coordinates (of course if we will sort everything in increasing order). Alright, then we want to find such $x < n$, so that $max(min(|a_i - b_{i + x}|, L - |a_i - b_{i + x}|))$ is minimal. (Where $i+x$ is by modulo $n$, of course). Let's make binary search on $ans$, then we want to check is there such $x$, so that $min(|a_i - b_{i + x}|, L - |a_i - b_{i + x}|) \leq ans$? If we will fix $i$, then set of good $x$ is just cyclical segment (you can find it with binary search or two pointers), and then we want to check that intersection of these segments is not empty. How to check it? We can split cyclic segment into two non-cyclic, and then just add on the segment offline, and then you need to check that there are some point with value $n$. So we can solve the problem in $O(n \cdot log L)$.
[ "binary search", "graph matchings", "greedy" ]
2,500
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <iomanip>\n#include <bitset>\n\nusing namespace std;\n\ntypedef long long ll;\n\nmt19937 rnd(228);\n\nvoid add(int my_l, int my_r, const vector <int> &b, vector <int> &cnt, int i)\n{\n int n = (int) b.size();\n int get_l = lower_bound(b.begin(), b.end(), my_l) - b.begin();\n int get_r = upper_bound(b.begin(), b.end(), my_r) - b.begin() - 1;\n if (get_l <= get_r)\n {\n int add_l = get_l - i + n;\n int add_r = get_r - i + n;\n if (add_l >= n) add_l -= n;\n if (add_r >= n) add_r -= n;\n if (add_l <= add_r)\n {\n cnt[add_l]++;\n cnt[add_r + 1]--;\n }\n else\n {\n cnt[add_l]++;\n cnt[0]++;\n cnt[add_r + 1]--;\n }\n }\n}\n\nint main()\n{\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n ios::sync_with_stdio(0);\n cin.tie(0);\n int n, L;\n cin >> n >> L;\n vector <int> a(n), b(n);\n for (int i = 0; i < n; i++)\n {\n cin >> a[i];\n }\n for (int i = 0; i < n; i++)\n {\n cin >> b[i];\n }\n sort(a.begin(), a.end());\n sort(b.begin(), b.end());\n int vl = -1, vr = L;\n while (vl < vr - 1)\n {\n int x = (vl + vr) / 2;\n vector <int> cnt(n + 1);\n for (int i = 0; i < n; i++)\n {\n int my_l = max(0, a[i] - x), my_r = min(L - 1, a[i] + x);\n int pref_add = -1, suf_add = L;\n if (a[i] - (L - x) >= my_l)\n {\n my_l = 0;\n }\n else\n {\n pref_add = max(-1, a[i] - (L - x));\n }\n if (a[i] + (L - x) <= my_r)\n {\n my_r = L - 1;\n }\n else\n {\n suf_add = min(L, a[i] + (L - x));\n }\n add(my_l, my_r, b, cnt, i);\n add(0, pref_add, b, cnt, i);\n add(suf_add, L - 1, b, cnt, i);\n }\n bool good = false;\n for (int i = 1; i <= n; i++)\n {\n cnt[i] += cnt[i - 1];\n }\n for (int i = 0; i < n; i++)\n {\n if (cnt[i] == n)\n {\n good = true;\n }\n }\n if (good)\n {\n vr = x;\n }\n else\n {\n vl = x;\n }\n }\n cout << vr << '\\n';\n}"
981
G
Magic multisets
In the School of Magic in Dirtpolis a lot of interesting objects are studied on Computer Science lessons. Consider, for example, the magic multiset. If you try to add an integer to it that is already presented in the multiset, each element in the multiset duplicates. For example, if you try to add the integer $2$ to the multiset $\{1, 2, 3, 3\}$, you will get $\{1, 1, 2, 2, 3, 3, 3, 3\}$. If you try to add an integer that is not presented in the multiset, it is simply added to it. For example, if you try to add the integer $4$ to the multiset $\{1, 2, 3, 3\}$, you will get $\{1, 2, 3, 3, 4\}$. Also consider an array of $n$ initially empty magic multisets, enumerated from $1$ to $n$. You are to answer $q$ queries of the form "add an integer $x$ to all multisets with indices $l, l + 1, \ldots, r$" and "compute the sum of sizes of multisets with indices $l, l + 1, \ldots, r$". The answers for the second type queries can be large, so print the answers modulo $998244353$.
For each value of $x$, let's maintain the set of elements on which this value is present. We will do this by maintaining segments in the set (don't worry, we will get rid of this unpleasant part later). Then you just need to take all the segments crossing $l$ or $r$, cut them into two smaller ones, and then everything inside all the segments inside the segment $[l..r]$ must be multiplied by $2$, and to the rest we must add $1$. How to do that? To do this, we store the segment tree, in each vertex modifiers $a$, $b$, such that all numbers $x$ in the subtree are equal to $a \cdot x + b$, not $x$. We can simply push and recalculate sum with these modifiers (look at the example code for more information about this). Then you need to add segment $[l..r]$ to the set. So we got the solution in $O((n + q) \cdot log n)$. But the not very nice part is maintaining the segments in the set. Let's get rid of this, take all the left and right bounds of the queries where it occurs, divide all the numbers into segments where the values will always be equal, and maintain (set? no, DSU!), if the segment does not contain a number, then let $par[i] = i$, otherwise $par[i] = i + 1$, (and, of course, use the path compression heuristics) then you can just start jumping from the left segment of the query, and merge neighboring segments, this solution is with the same asympotitcs, but much nicer for implementation.
[ "data structures" ]
2,500
"/*\n Author: isaf27 (Ivan Safonov)\n*/\n\n//#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n//defines\ntypedef long long ll;\ntypedef double ld;\n#define TIME clock() * 1.0 / CLOCKS_PER_SEC\n#define fast_read cin.sync_with_stdio(0)\n#define nul point(0, 0)\n#define str_to_int(stroka) atoi(stroka.c_str())\n#define str_to_ll(stroka) atoll(stroka.c_str())\n#define str_to_double(stroka) atof(stroka.c_str())\n#define what_is(x) cerr << #x << \" is \" << x << endl\n#define solve_system int number; cin >> number; for (int i = 0; i < number; i++) solve()\n#define solve_system_scanf int number; scanf(\"%d\", &number); forn(i, 0, number) solve()\n\n//permanent constants\nconst ld pi = 3.141592653589793238462643383279;\nconst ld log23 = 1.58496250072115618145373894394781;\nconst ld eps = 1e-10;\nconst ll INF = 1e18 + 239;\nconst ll prost = 239;\nconst int two = 2;\nconst int th = 3;\nconst ll MOD = 1e9 + 7;\nconst ll MOD2 = MOD * MOD;\nconst int BIG = 1e9 + 239;\nconst int alf = 26;\nconst int dx[4] = {-1, 0, 1, 0};\nconst int dy[4] = {0, 1, 0, -1};\nconst int dxo[8] = {-1, -1, -1, 0, 1, 1, 1, 0};\nconst int dyo[8] = {-1, 0, 1, 1, 1, 0, -1, -1};\nconst int dig = 10;\nconst string str_alf = \"abcdefghijklmnopqrstuvwxyz\";\nconst string str_alf_big = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\nconst int digarr[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};\nconst int bt = 31;\n\n//easy functions\ntemplate< typename T >\ninline T gcd(T a, T b) { return a ? gcd(b % a, a) : b; }\ntemplate< typename T >\ninline T lcm(T a, T b) { return (a / gcd(a, b)) * b; }\ninline bool is_down(char x) { return ('a' <= x && x <= 'z'); }\ninline bool is_upper(char x) { return ('A' <= x && x <= 'Z'); }\ninline bool is_digit(char x) { return ('0' <= x && x <= '9'); }\nll power(ll a, int k)\n{\n ll ans = 1;\n while (k)\n {\n if (k & 1) ans = (ans * a) % MOD;\n ans = (ans * ans) % MOD;\n k >>= 1;\n }\n return ans;\n}\n\n//random\nmt19937 rnd(239);\n\n//constants\nconst int M = 2 * 1e5 + 239;\nconst int N = 2 * 1e3 + 239;\nconst int L = 20;\nconst int T = (1 << 19);\nconst int B = trunc(sqrt(M)) + 1;\nconst int X = 1e4 + 239;\nconst ll D = 998244353;\n\n// Code starts here\n\nstruct dsu\n{\n vector<int> parent, rg, r;\n\n dsu()\n {\n parent = rg = r = {};\n }\n\n dsu(int n)\n {\n parent.resize(n);\n rg.resize(n);\n r.resize(n);\n for (int i = 0; i < n; i++)\n parent[i] = i, r[i] = 0, rg[i] = i + 1;\n }\n\n int find_set(int a)\n {\n if (parent[a] == a)\n return a;\n return parent[a] = find_set(parent[a]);\n }\n\n void merge_set(int a, int b)\n {\n a = find_set(a);\n b = find_set(b);\n if (a == b)\n return;\n if (r[a] > r[b])\n swap(a, b);\n rg[b] = max(rg[b], rg[a]);\n parent[a] = b;\n if (r[a] == r[b]) r[b]++;\n }\n\n bool is_connect(int a, int b)\n {\n return find_set(a) == find_set(b);\n }\n\n int getnxt(int a)\n {\n return rg[find_set(a)];\n }\n};\n\n//segtree\nll tree[T];\nll a[T], b[T];\n\ninline void build(int i, int l, int r)\n{\n a[i] = 1;\n b[i] = 0;\n tree[i] = 0;\n if (r - l == 1) return;\n int mid = (l + r) >> 1;\n build(2 * i + 1, l, mid);\n build(2 * i + 2, mid, r);\n}\n\ninline void push(int i, int l, int r)\n{\n tree[i] = (tree[i] * a[i] + b[i] * (ll)(r - l)) % D;\n if (r - l != 1)\n {\n a[2 * i + 1] = (a[2 * i + 1] * a[i]) % D;\n b[2 * i + 1] = (b[2 * i + 1] * a[i] + b[i]) % D;\n a[2 * i + 2] = (a[2 * i + 2] * a[i]) % D;\n b[2 * i + 2] = (b[2 * i + 2] * a[i] + b[i]) % D;\n }\n a[i] = 1;\n b[i] = 0;\n}\n\ninline void change(int i, int l, int r, int ql, int qr, int t)\n{\n push(i, l, r);\n if (qr <= l || r <= ql) return;\n if (ql <= l && r <= qr)\n {\n if (t == 0)\n {\n a[i] = (a[i] * 2LL) % D;\n b[i] = (b[i] * 2LL) % D;\n }\n else\n {\n b[i] = (b[i] + 1) % D;\n }\n push(i, l, r);\n return;\n }\n int mid = (l + r) >> 1;\n change(2 * i + 1, l, mid, ql, qr, t);\n change(2 * i + 2, mid, r, ql, qr, t);\n tree[i] = (tree[2 * i + 1] + tree[2 * i + 2]) % D;\n}\n\ninline ll getsum(int i, int l, int r, int ql, int qr)\n{\n push(i, l, r);\n if (qr <= l || r <= ql) return 0;\n if (ql <= l && r <= qr) return tree[i];\n int mid = (l + r) >> 1;\n return (getsum(2 * i + 1, l, mid, ql, qr) + getsum(2 * i + 2, mid, r, ql, qr)) % D;\n}\n//end\n\nint n, q;\nvector<vector<int> > qr;\nvector<vector<int> > vx(M);\nvector<vector<pair<int, int> > > seg(M);\nvector<vector<bool> > used(M);\nvector<dsu> d;\n\ninline void upd(int x, int l, int r)\n{\n vector<int> nw;\n int i = lower_bound(seg[x].begin(), seg[x].end(), make_pair(l, 0)) - seg[x].begin();\n while (i < seg[x].size())\n {\n if (seg[x][i].second > r) break;\n if (used[x][i])\n {\n i = d[x].getnxt(i);\n continue;\n }\n nw.push_back(i);\n i = d[x].getnxt(i);\n }\n for (int i : nw) change(0, 0, n, seg[x][i].first, seg[x][i].second + 1, 1);\n vector<int> a;\n a.push_back(l);\n for (int i : nw)\n {\n a.push_back(seg[x][i].first - 1);\n a.push_back(seg[x][i].second + 1);\n }\n a.push_back(r);\n for (int i = 0; i < a.size(); i += 2)\n {\n if (a[i] > a[i + 1]) continue;\n change(0, 0, n, a[i], a[i + 1] + 1, 0);\n }\n for (int i : nw)\n {\n used[x][i] = true;\n if (i != 0 && used[x][i - 1]) d[x].merge_set(i - 1, i);\n if (i != (int)seg[x].size() - 1 && used[x][i + 1]) d[x].merge_set(i, i + 1);\n }\n}\n\ninline ll gett(int l, int r)\n{\n return getsum(0, 0, n, l, r + 1);\n}\n\nint main()\n{ /*\n #ifndef ONLINE_JUDGE\n freopen(\"input.txt\", \"r\", stdin);\n freopen(\"output.txt\", \"w\", stdout);\n #endif /**/\n fast_read;\n cin >> n >> q;\n for (int i = 0; i < q; i++)\n {\n int t;\n cin >> t;\n if (t == 1)\n {\n int l, r, x;\n cin >> l >> r >> x;\n l--, r--, x--;\n qr.push_back({l, r, x});\n vx[x].push_back(l);\n vx[x].push_back(r);\n }\n else\n {\n int l, r;\n cin >> l >> r;\n l--, r--;\n qr.push_back({l, r});\n }\n }\n d.resize(n);\n for (int i = 0; i < n; i++)\n {\n sort(vx[i].begin(), vx[i].end());\n vx[i].resize(unique(vx[i].begin(), vx[i].end()) - vx[i].begin());\n for (int x = 0; x < vx[i].size(); x++)\n {\n seg[i].push_back(make_pair(vx[i][x], vx[i][x]));\n if (x + 1 != vx[i].size())\n if (vx[i][x + 1] - vx[i][x] != 1)\n seg[i].push_back(make_pair(vx[i][x] + 1, vx[i][x + 1] - 1));\n }\n used[i].assign(seg[i].size(), false);\n d[i] = dsu(seg[i].size());\n }\n build(0, 0, n);\n for (int z = 0; z < q; z++)\n {\n if (qr[z].size() == 3)\n upd(qr[z][2], qr[z][0], qr[z][1]);\n else\n cout << gett(qr[z][0], qr[z][1]) << \"\\n\";\n }\n return 0;\n}"
981
H
K Paths
You are given a tree of $n$ vertices. You are to select $k$ (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and the latter set should be non-empty. Compute the number of ways to select $k$ paths modulo $998244353$. The paths are enumerated, in other words, two ways are considered distinct if there are such $i$ ($1 \leq i \leq k$) and an edge that the $i$-th path contains the edge in one way and does not contain it in the other.
For each vertex $v$ let's calculate $f_v$ - number of ways to choose $k$ ends for paths in their subtree, such that these paths are edge-intersecting, and $g_v$ - sum of $f_u$ by all vertices $u$ in subtree of $v$. Let $sz_v$ will be number of vertices in subtree of $v$. Then let $P(x) = (1 + x \cdot sz_{u_{0}}) \cdot (1 + x \cdot sz_{u_{1}}) \ldots \cdot (1 + x \cdot sz_{u_{deg - 1}})$, (where $u_0, u_1, \ldots, u_{deg - 1}$ are the childs of vertex $v$), $= \sum(a_k \cdot x^k)$ How to calculate $P(x)$? We will use divide and conquer, let's recursively calculate answer for first half of element, for second, and then multiplicate. $T(n) = 2 T(n / 2) + O(n log n) = O(n log^2 n)$ Note, that degree of polynom is not $n$, but $deg_v$!. Then $f_v = \sum(a_x \cdot C_k^x \cdot x!)$. Then for fixed non-vertical path $u \to v$, number of ways to choose $k$ paths, such that their intersection is $u \to v$ is $f_u \cdot f_v$. We can sum this up for each non-vertical path with simple tree dp. So we are working in $O(deg_v log^2 n)$ for fixed $v$, summing up for each vertex we can get that this part of solution is working in $O(n log^2 n)$. Let fix one end of vertical path $v$ and it's son $u$, such that second end of vertical path is inside his subtree, Then let $Q(x) = P(x) \cdot(1 + x \cdot (n - sz_v)) / (1 + x \cdot sz_u) = \sum(b_k \cdot x^k)$, when we need add $\sum(b_x \cdot C_k^x \cdot x!) \cdot g_u$ to answer. Then we can note, that (for fixed $v$) number of distinct $sz_u$'s - $O(\sqrt{n})$ And for each $sz_u$ we can get $Q(x)$ in $O(deg_v)$, at first we need to calculate (one time!) $P(x) \cdot(1 + x \cdot (n - sz_v)) = \sum(c_k \cdot x^k)$, and then $b_0 = 1$, and $b_x = c_x - b_{x-1} \cdot sz_u$. So, this part is working in $O(deg_v \cdot \sqrt{n})$ for fixed $v$, summing up for each vertices we can get that this part of solution is working in $O(n \sqrt{n})$, so we solved the task in $O(n log^2 n + n \sqrt{n})$
[ "combinatorics", "data structures", "dp", "fft", "math" ]
3,100
"#pragma GCC optimize(\"O3\")\n#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <unordered_set>\n#include <iomanip>\n#include <bitset>\n#include <sstream>\n\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\n#define TIME (clock() * 1.0 / CLOCKS_PER_SEC)\n\nmt19937 rnd(239);\n\nconst ld pi = acos(-1.0);\nconst ll INF = 1e18 + 239;\nconst int BIG = 1e9 + 239;\n//const ll MOD = 1e9 + 7;\n//const ll MOD2 = MOD * MOD;\nconst int M = 2e5 + 239;\nconst int T = (1 << 19);\n\nconst ll MOD = 998244353;\nconst ll root = 3;\nconst ll sub = 15311432;\n\nll st[T];\n\ninline ll power(ll a, ll b)\n{\n if (b == 0)\n return 1;\n ll t = power(a, (b >> 1));\n t = (t * t) % MOD;\n if (b & 1)\n return (t * a) % MOD;\n return t;\n}\n\ninline int inv(int n, int b)\n{\n int ans = 0;\n for (int i = 0; i < b; i++)\n {\n ans = (ans << 1) + (n & 1);\n n >>= 1;\n }\n return ans;\n}\n\nint p;\nll w;\n\nmap <vector <ll>, vector <ll> > pq;\n\ninline void fft(const vector<ll> &a, vector <ll> &b)\n{\n if (pq.count(a))\n {\n b = pq[a];\n return;\n }\n b.resize(a.size());\n for (int i = 0; i < a.size(); i++)\n b[i] = a[inv(i, p)];\n for (int z = 0; z < p; z++)\n {\n int u = (1 << z);\n for (int i = 0; i < (1 << p); i++)\n {\n int ps = i >> z;\n if ((ps & 1) == 0)\n {\n int t = i & (u - 1);\n ll bi = (b[i] + st[t << (p - z - 1)] * b[i + u]) % MOD;\n ll bii = (b[i] + st[(t + u) << (p - z - 1)] * b[i + u]) % MOD;\n b[i] = bi;\n b[i + u] = bii;\n }\n }\n }\n pq[a] = b;\n}\n\ninline vector<ll> sum(vector<ll> a, vector<ll> b)\n{\n\tint n = max((int)a.size(), (int)b.size());\n\tvector<ll> ans(n, 0);\n\twhile (a.size() < n) a.push_back(0);\n\twhile (b.size() < n) b.push_back(0);\n\tfor (int i = 0; i < n; i++) ans[i] = (a[i] + b[i]) % MOD;\n\treturn ans;\n}\n\nvector <ll> ta, tb;\nvector<ll> as;\n\n\ninline vector<ll> multiply(vector<ll> a, vector<ll> b)\n{\n int k = (a.size() + b.size() + 1);\n p = trunc(log2(k)) + 1;\n while (a.size() < (1 << p)) a.push_back(0);\n while (b.size() < (1 << p)) b.push_back(0);\n w = power(sub, (1 << (23 - p)));\n st[0] = 1LL;\n for (int i = 1; i < (1 << p); i++)\n st[i] = (st[i - 1] * w) % MOD;\n fft(a, ta);\n fft(b, tb);\n vector<ll> v;\n for (int i = 0; i < (1 << p); i++)\n v.push_back((ta[i] * tb[i]) % MOD);\n fft(v, as);\n ll d = power((1 << p), MOD - 2);\n for (int i = 0; i < (1 << p); i++)\n as[i] = (d * as[i]) % MOD;\n reverse(as.begin() + 1, as.end());\n while (as.back() == 0) as.pop_back();\n return as;\n}\n\nint n, k, kol[M];\nvector <int> v[M];\nll f[M], ans;\nll mlt;\nint sz;\nll a[M], s[M];\nll u, kf[M], fact[M];\n\ninline pair<vector<ll>, vector<ll> > func(int l, int r)\n{\n\tif (r - l == 1)\treturn {{s[l], (u * s[l]) % MOD}, {1, a[l]}};\n\tint mid = (l + r) >> 1;\n\tpair<vector<ll>, vector<ll> > a1 = func(l, mid);\n\tpair<vector<ll>, vector<ll> > a2 = func(mid, r);\n\treturn make_pair(sum(multiply(a1.first, a2.second), multiply(a1.second, a2.first)), multiply(a1.second, a2.second));\n}\n\nll dfs(int p, int pr)\n{\n kol[p] = 1;\n int szt = 0;\n vector <ll> aa, sa;\n for (int i : v[p])\n if (pr != i)\n {\n ll now = dfs(i, p);\n kol[p] += kol[i];\n aa.push_back(kol[i]);\n sa.push_back(now);\n }\n sz = aa.size();\n for (int i = 0; i < sz; i++)\n {\n a[i] = aa[i];\n s[i] = sa[i];\n }\n u = n - kol[p];\n ll sum = 0;\n for (int i = 0; i < sz; i++) sum = (sum + s[i]) % MOD;\n ll sqr = 0;\n for (int i = 0; i < sz; i++) sqr = (sqr + s[i] * s[i]) % MOD;\n sqr = (sum * sum - sqr) % MOD;\n if (sqr < 0) sqr += MOD;\n ans = (ans + sqr * mlt) % MOD;\n if (sz == 0)\n {\n return 1;\n }\n pair<vector<ll>, vector<ll> > t = func(0, sz);\n int s = max((int)t.first.size(), (int)t.second.size());\n for (int i = 0; i < min(s, k + 1); i++)\n {\n\t\tif ((int)t.first.size() > i) ans = (ans + kf[i] * t.first[i]) % MOD;\n\t\tif ((int)t.second.size() > i)\n\t\t{\n sum = (sum + kf[i] * t.second[i]) % MOD;\n\t\t}\n\t}\n\treturn sum;\n}\n\nint main()\n{ //*\n //freopen(\"test.in\", \"r\", stdin);\n //freopen(\"test.out\", \"w\", stdout); /**/\n ios::sync_with_stdio(0);\n cin.tie(0);\n\tcin >> n >> k;\n\tif (k == 1)\n\t{\n\t\tcout << (((ll)n * (ll)(n - 1)) / 2) % MOD;\n\t\treturn 0;\n\t}\n\tfor (int i = 0; i < n - 1; i++)\n\t{\n\t\tint s, f;\n\t\tcin >> s >> f;\n\t\ts--, f--;\n\t\tv[s].push_back(f);\n\t\tv[f].push_back(s);\n\t}\n\tfact[0] = 1;\n\tfor (int i = 0; i < k; i++) fact[i + 1] = (fact[i] * (ll)(i + 1)) % MOD;\n\tfor (int i = 0; i <= k; i++) kf[i] = (fact[k] * power(fact[k - i], MOD - 2)) % MOD;\n ans = 0;\n mlt = power(2, MOD - 2);\n dfs(0, -1);\n cout << ans;\n return 0;\n}"
982
A
Row
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold: - There are no neighbors adjacent to anyone seated. - It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is "maximal". Note that the first and last seats are \textbf{not} adjacent (if $n \ne 2$).
Seating is the maximum when it does not exist two ones or three zeros together. It is also necessary to carefully process the ends of the series - it is necessary to check that you can not put a person on the most right or the most left chairs.
[ "brute force", "constructive algorithms" ]
1,200
null
982
B
Bus of Characters
In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct. Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers: - an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; - an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.
Note that the final introvert-extrovert pairs are uniquely determined, and that using the stack, it is possible to recover which extrovert to which introvert will sit (note that the zeros and ones will form the correct bracket sequence). Then one of the solutions may be as follows: Sort the array of the lengths of the rows in ascending order For each introvert write the number of the next free row and add it to the stack For each extrovert write the last number from the stack and remove it from there
[ "data structures", "greedy", "implementation" ]
1,300
null
982
C
Cut 'em all!
You're given a tree with $n$ vertices. Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
Note that if there is an edge that can be removed, we can do it without any problem. Let's consider such edge that in one of the obtained subtrees it is impossible to delete more anything else, and its removal is possible. What happens if we delete it in the tree? Relative to the other end of the edge, the odd-even balance of the subtree has not changed, which means that the edge has not been affected by further deletions. Which means if we remove it, the answer will be better. This is followed by a greedy solution: in dfs we count the size of the subtree for each vertex, including the current vertex, and if it is even, then the edge from the parent (if it exists) can be removed.
[ "dfs and similar", "dp", "graphs", "greedy", "trees" ]
1,500
null
982
D
Shark
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations. Max is a young biologist. For $n$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $k$ that if the shark in some day traveled the distance strictly less than $k$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $k$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $k$. The shark never returned to the same location after it has moved from it. Thus, in the sequence of $n$ days we can find consecutive nonempty segments when the shark traveled the distance less than $k$ in each of the days: each such segment corresponds to one location. Max wants to choose such $k$ that the lengths of all such segments are equal. Find such integer $k$, that the number of locations is as large as possible. If there are several such $k$, print the smallest one.
Let's sort the array and insert the numbers in the sort order from smaller to larger. Using the data structure "disjoint set union" we can easily maintain information about the current number of segments, as well as using the map within the function of union, and information about the current size of segments (locations) too. Then it remains only to update the answer when it's needed.
[ "brute force", "data structures", "dsu", "trees" ]
1,900
null
982
E
Billiard
Consider a billiard table of rectangular size $n \times m$ with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture). There is one ball at the point $(x, y)$ currently. Max comes to the table and strikes the ball. The ball starts moving along a line that is parallel to one of the axes or that makes a $45^{\circ}$ angle with them. We will assume that: - the angles between the directions of the ball before and after a collision with a side are equal, - the ball moves indefinitely long, it only stops when it falls into a pocket, - the ball can be considered as a point, it falls into a pocket if and only if its coordinates coincide with one of the pockets, - initially the ball is not in a pocket. Note that the ball can move along some side, in this case the ball will just fall into the pocket at the end of the side. Your task is to determine whether the ball will fall into a pocket eventually, and if yes, which of the four pockets it will be.
If you symmetrically reflect a rectangle on the plane relative to its sides, the new trajectory of the ball will be much easier. Linear trajectory if be correct. One possible solution is: If the vector is directed at an angle of 90 degrees to the axes, then write the if-s. Otherwise, turn the field so that the impact vector becomes $(1, 1)$. Write the equation of the direct motion of the ball: $- 1 \cdot x + 1 \cdot y + C = 0$. If we substitute the initial position of the ball, we find the coefficient $C$. Note that in the infinite tiling of the plane the coordinates of any holes representable in the form $(k_{1} \cdot n, k_{2} \cdot m)$. Substitute the coordinates of the points in the equation of the line of the ball. The Diophantine equation $a \cdot k_{1} + B \cdot k_{2} = C$is obtained. It is solvable if $C | gcd(A, B)$. Otherwise, there are no solutions. Of all the solutions of this Diophantine equation, we are interested in the smallest on the positive half-axis. By finding $k_{1}, k_{2}$ it is easy to get the coordinates of the corresponding pocket Rotate the field back if required.
[ "geometry", "number theory" ]
2,600
null
982
F
The Meeting Place Cannot Be Changed
Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping. Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements.
Let's assume that solution exists and will looking for solution relying on this assumption. At the end will check found "solution" in linear time, and if it is not real solution, then assumption wasn't right. If solution exists, then intersection (by vertices) of all cycles is not empty. Let's take any one cycle and call it "main cycle". Let's imagine this "main cycle" as circle directed clockwise. And let's mark all required vertices of intersection of all cycles on this circle (this vertices are the answer). Consider only cycles which leave "main cycle", come back to the "main cycle", and then moves on the "main cycle" to the begining. Every such cycle when comes back to the "main cycle" DOES NOT jump over any marked vertex of the answer, in terms of direction of the "main cycle" (otherwise answer not exists, but we assumed, that it exists) (if cycle comes back to the same vertex, then by definition it jumped over the whole "main cycle", not 0). Draw the arc from the vertex, where cycle comes back to the "main cycle" till the vertex, where it leaves "main cycle", in the direction of the "main cycle". Vertices not covered by this arc can't be the answer. Intersection of all considered cycles is marked by intersection of all such arcs. Now was not considered only cycles which some times leave "main cycle" and some times comes back to it. But intersection of such cycle with the "main cycle" is the same as intersection of simple cycles from previous paragraph between adjacent leave/comebacks. Therefore such cycles may be ignored. For searching the answer we must mark arcs between leaves/comebacks of the main cycle. We do this by starting dfs from all vertices of the "main cycle" and trying to come back to it as far as possible (distance measured as the number of vertices of the "main cycle" between leave and comeback). As were noticed early, cycles does not jump over the answer. Therefore dfses started between boundaries of the answer are aspires to this boundary in direction of the "main cycle". Therefore if we selected the most far vertex in one dfs(u) reached from one start point v0, this vertex for dfs(u) reached from other start point v1 will be the most far too. And we can run all dfses with common "used" array, caching the most far vertex in it. Finally the solution is so: 1) find the "main cycle" and sort vertices in it, 2) start dfses from vertices of the "main cycle" and mark arcs between finish and start, 3) intersect all arcs and take answer from intersection, 4) verify answer by deleting it from graph and trying to find any other cycle, if it founded, then assumption was wrong and solution doesn't exists else print the answer.
[ "dfs and similar", "graphs" ]
2,700
null
983
A
Finite or not?
You are given several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction. A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
First, if $p$ and $q$ are not coprime, divide them on $\gcd(p,q)$. Fraction is finite if and only if there is integer $k$ such that $q \mid p \cdot b^k$. Since $p$ and $q$ are being coprime now, $q \mid b^k \Rightarrow$ all prime factors of $q$ are prime factors of $b$. Now we can do iterations $q = q \div \gcd(b,q)$ while $\gcd(q,b) \ne 1$. If $q \ne 1$ after iterations, there are prime factors of $q$ which are not prime factors of $b \Rightarrow$ fraction is Infinite, else fraction is Finite. But this solution works in $O(nlog^210^{18})$. Let's add $b=\gcd(b,q)$ in iterations and name iterations when $\gcd(b,q)$ changes iterations of the first type and when it doesn't change - iterations of the second type. Iterations of second type works summary in $O(\log10^{18})$. Number of iterations of the first type is $O(\log10^{18})$ too but on each iteration $b$ decreases twice. Note that number of iterations in Euclid's algorithm is equal to number of this decreases. So iterations of first type works in $O(\log10^{18})$ summary. Total time complexity is $O(n\log10^{18})$
[ "implementation", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; while (n--) { long long p, q, b; cin >> p >> q >> b; long long g = gcd(p, q); q /= g; b = gcd(q, b); while (b != 1) { while (q % b == 0) q /= b; b = gcd(q, b); } if (q == 1) cout << "Finite\n"; else cout << "Infinite\n"; } return 0; }
983
B
XOR-pyramid
For an array $b$ of length $m$ we define the function $f$ as \begin{center} $ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $ \end{center} where $\oplus$ is bitwise exclusive OR. For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$ You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$.
Let's calculate $f(a)$ recursively and save arrays from each level of recursion. We get two-dimencional array $dp[n][n]$ and $dp[n][1]=f(a)$. Now let's view recursive calculation for $f(a_l \ldots a_r)$. You can see what array of $i$-th level of recursion is $dp[i][l\ldots r-i+1]\Rightarrow dp[r-l+1][l]=f(a_l \ldots a_r)$ (numbeer of levels of recursion is length of segment). To calculate maximum of all sub-segments for each segment, replace $dp[i][j]$ on $\max(dp[i][j],dp[i-1][j],dp[i-1][j+1])$. Now answer of question $l,r$ is $dp[r-l+1][l]$. Overall time complexity is $O(n^2 + q)$.
[ "dp" ]
1,800
#include <bits/stdc++.h> using namespace std; int run(); int main() { #ifdef home freopen("i", "r", stdin); freopen("d", "w", stderr); #endif cout.precision(15); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); run(); } const int N = 5000; int a[N]; int dp[N][N]; int run() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; dp[0][i] = a[i]; } for (int i = 1; i < n; i++) { for (int j = 0; j <= n - i; j++) { dp[i][j] = dp[i - 1][j + 1] ^ dp[i - 1][j]; } } for (int i = 1; i < n; i++) { for (int j = 0; j < n - i; j++) { dp[i][j] = max({dp[i][j], dp[i - 1][j], dp[i - 1][j + 1]}); } } int q; cin >> q; for (int i = 0; i < q; i++) { int l, r; cin >> l >> r; --l; int len = r - l - 1; cout << dp[len][l] << '\n'; } }
983
C
Elevator
You work in a big office. It is a $9$ floor building with an elevator that can accommodate up to $4$ people. It is your responsibility to manage this elevator. Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator. According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order. The elevator has two commands: - Go up or down one floor. The movement takes $1$ second. - Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends $1$ second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor $1$. You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor $1$.
This problem is inspired by living in the house of $9$ floors with the elevator, which can accommodate up to $4$ people. What a surprise! We have a strict order. So let's make $dp[i][state] =$ minimal possible time, where $i$ means that first $i$ employees already came in the elevator (and possibly came out). So, what is a $state$? Let's store something what will allow us to determine the state. For this purpose we want to know the floor, where the elevator currently is, and number of people, who want to reach each floor. So, it's $10$ integers. Let's estimate the number of states: floor takes $9$ values, $state$ can take ${\binom{9}{4}}+{\binom{9}{3}}+{\binom{9}{1}}+{\binom{9}{0}}+{\binom{9}{0}}=256$ (Wow!). Also let's notice, that we don't want to visit floor of nobody in the elevator don't want to go there and the next person isn't on that floor. So we have not more than $5$ interesting floors for each $state$. Let's say the total count of states is $s = 5 \cdot 256$. Now we've got two different solutions. The fast one is we say we go from the floor $a[i]$ to the floor $a[i + 1]$ and iterate over the persons who we let come in on the way. The slow one is to run Dijkstra for each $i$: from $state$ we can go to the floor and let somebody come out or go to the floor $a[i + 1]$. Now, when we calculated answers for $i - 1$, we can calculate $dp[i][state] = 1 + dp[i - 1][state]$, if state has floor equals to $a_{i}$ and there are no more than $3$ people inside. The answer will be in $dp[n][floor = j & elevator is empty]$ for $j\in[1,9]$. Asymptotics is $O(n \cdot s)$ or $O(n \cdot s \cdot log(s))$
[ "dp", "graphs", "shortest paths" ]
2,400
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> #include <vector> #include <map> #include <set> #include <bitset> #include <queue> #include <stack> #include <sstream> #include <cstring> #include <numeric> #include <ctime> #include <cassert> #define re return #define fi first #define se second #define mp make_pair #define pb emplace_back #define all(x) (x).begin(), (x).end() #define sz(x) ((int) (x).size()) #define rep(i, n) for (int i = 0; i < (n); i++) #define rrep(i, n) for (int i = (n) - 1; i >= 0; i--) #define y0 y32479 #define y1 y95874 #define fill(x, y) memset(x, y, sizeof(x)) #define sqr(x) ((x) * (x)) #define sqrt(x) sqrt(abs(x)) #define unq(x) (x.resize(unique(all(x)) - x.begin())) #define spc(i,n) " \n"[i == n - 1] #define next next239 #define prev prev239 #define ba back() #define last(x) x[sz(x) - 1] #define deb(x) cout << #x << " = " << (x) << endl #define deba(x) do { cout << #x << " (size: " << sz(x) << ") = " << \ "{"; for (auto o : x) cout << o << ","; cout << "}" << endl;} while (0) using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<string> vs; typedef long long ll; typedef pair<ll, ll> pll; typedef vector<ll> vll; typedef long double LD; typedef double D; template<class T> T abs(T x) { return x > 0 ? x : -x;} template<class T> T toString(T x) { ostringstream sout; sout << x; return sout.str(); } int nint() { int x; scanf("%d", &x); re x; } const ll mod = 1000000000 + 7; int m; int n; ll ans; int a[2050], b[2050]; int table[2050][1050]; vi split(int x) { vi ans; rep(i, 3) { if (x % 10) ans.pb(x % 10); x /= 10; } re ans; } inline int merge(vi &v, int x) { int ans = 0; rep(i, 3) { ans *= 10; if (i < sz(v) && v[i] != x) ans += v[i]; } re ans; } inline int get1(int l, int r, int x) { re min(abs(x - l), abs(x - r)) + r - l; } inline int get2(int l, int r, int x1, int x2) { re min(abs(x1 - l) + abs(x2 - r), abs(x1 - r) + abs(x2 - l)) + r - l; } int getans(int p, int cur) { int &ans = table[p][cur]; if (ans != -1) re ans; int pos = a[p]; vi v = split(cur); v.pb(b[p]); sort(all(v)); if (p == n - 1) { ans = get1(v[0], v.back(), pos); re ans; } ans = mod; int ne = a[p + 1]; if (sz(v) < 4) ans = min(ans, getans(p + 1, merge(v, ne)) + abs(ne - pos)); rep(i, sz(v)) { if (i && (v[i] == v[i - 1])) continue; for (int j = i; j < sz(v); j++) { if (j < sz(v) - 1 && v[j] == v[j + 1]) continue; int tmp = get2(v[i], v[j], pos, ne); vi tv; rep(k, sz(v)) { if (k < i || k > j) tv.pb(v[k]); } ans = min(ans, tmp + getans(p + 1, merge(tv, ne))); } } re ans; } int main() { #ifdef LOCAL_BOBER freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); srand((int)time(0)); #else //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif cin >> n; rep(i, n) cin >> a[i] >> b[i]; fill(table, -1); cout << getans(0, 0) + a[0] - 1 + 2 * n; }
983
D
Arkady and Rectangles
Arkady has got an infinite plane painted in color $0$. Then he draws $n$ rectangles filled with paint with sides parallel to the Cartesian coordinate axes, one after another. The color of the $i$-th rectangle is $i$ (rectangles are enumerated from $1$ to $n$ in the order he draws them). It is possible that new rectangles cover some of the previous ones completely or partially. Count the number of different colors on the plane after Arkady draws all the rectangles.
First let's compress the coordinates. Now all the coordinates are in $[0, 2n)$. Now we do scanline on $x$ coordinate with segment tree on $y$ coordinate. Let's talk about segment tree structute. In each vertex we store: Set of colors which cover the whole segment. If color covers a segment, we don't push it to it childs ($colors[v]$) Maximal visible color in subtree which isn't in the answer ($max[v]$) Minimal visible color in subtree ($min[v]$) For the vertex max and min can be calculated as: If $colors$ isn't empty and max value in $colors$ is more than max in children: If it's already in the answer or it's less than min in children, $max = -1$. Otherwise $max = max \ in \ colors$ Otherwise $max = max \ in \ children$ If $colors$ isn't empty $min = max(max \ in \ colors, min \ in \ children)$ Otherwise $min = min \ in \ children$ Now in scanline we: Add all the segments, starting at this point Remove all the segments, ending at this point While $max[root]$ isn't $-1$ we put it into $answer$ and recalculate everything by readding this segment to tree. At the end we know all visible colors and print the number of them. Asymptotics is $O(n \cdot log(n) + n \cdot log^2(n))$
[ "data structures" ]
3,300
#include <bits/stdc++.h> using namespace std; namespace solution { int run(); } int main() { #ifdef home freopen("i", "r", stdin); freopen("d", "w", stderr); #endif cout.precision(15); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); solution::run(); } namespace solution { const int SZ = 1500500; const int N = 100500; int x1[N], x2[N], y1[N], y2[N]; bool erased[N]; priority_queue<int> els[SZ]; int mn[SZ]; int mx[SZ]; bool seen[N]; enum { ACTION_ADD, ACTION_ERASE, ACTION_VOID }; void recalc(int cur) { int max_in_child = max(mx[cur * 2], mx[cur * 2 + 1]); while (!els[cur].empty() && erased[els[cur].top()]) { els[cur].pop(); } int max_in_vertex = els[cur].empty() ? -1 : els[cur].top(); int min_in_child = min(mn[cur * 2], mn[cur * 2 + 1]); if (max_in_vertex > max_in_child) { if (seen[max_in_vertex] || max_in_vertex < min_in_child) { mx[cur] = -1; } else { mx[cur] = max_in_vertex; } } else { mx[cur] = max_in_child; } mn[cur] = max(max_in_vertex, min_in_child); } void add(int cur, int lb, int rb, int id, int action, int l = 0, int r = 2 * N) { if (lb >= r || rb <= l) { return; } if (lb <= l && rb >= r) { if (action == ACTION_ADD) { els[cur].push(id); } recalc(cur); return; } int mid = (l + r) / 2; add(cur * 2, lb, rb, id, action, l, mid); add(cur * 2 + 1, lb, rb, id, action, mid, r); recalc(cur); } set<int> cx, cy; unordered_map<int, int> id_x, id_y; vector<pair<int, int> > events[2 * N]; int run() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> x1[i] >> y1[i] >> x2[i] >> y2[i]; cx.insert(x1[i]); cx.insert(x2[i]); cy.insert(y1[i]); cy.insert(y2[i]); } int j = 0; for (auto x : cx) { id_x[x] = j++; } j = 0; for (auto y : cy) { id_y[y] = j++; } for (int i = 0; i < n; i++) { x1[i] = id_x[x1[i]]; x2[i] = id_x[x2[i]]; y1[i] = id_y[y1[i]]; y2[i] = id_y[y2[i]]; events[x1[i]].push_back({i, ACTION_ADD}); events[x2[i]].push_back({i, ACTION_ERASE}); } for (int i = 0; i < SZ; i++) { mx[i] = -1; } int cnt_x = id_x.size(); for (int i = 0; i < cnt_x; i++) { for (auto e : events[i]) { int id = e.first; int action = e.second; if (action == ACTION_ERASE) { erased[id] = true; } add(1, y1[id], y2[id], id, action); } while (mx[1] >= mn[1]) { int id = mx[1]; seen[id] = true; add(1, y1[id], y2[id], id, ACTION_VOID); } } int ans = 1; for (int i = 0; i < n; i++) { if (seen[i]) { ans++; } } cout << ans; } }
983
E
NN country
In the NN country, there are $n$ cities, numbered from $1$ to $n$, and $n - 1$ roads, connecting them. There is a roads path between any two cities. There are $m$ bidirectional bus routes between cities. Buses drive between two cities taking the shortest path with stops in every city they drive through. Travelling by bus, you can travel from any stop on the route to any other. You can travel between cities only by bus. You are interested in $q$ questions: is it possible to get from one city to another and what is the minimum number of buses you need to use for it?
Let's say we go down when we go towards the root, and we go up when we go against the root. Also we say that vertex $a$ lower than vertex $b$ if $a$ is closer to the root. Each way from $v$ to $u$ can be represented as two parts: at first we go down from $v$ to $lca$ and then we go up from $lca$ to $u$. Let's say we have to use $a$ buses to go from $v$ to $lca$ and $b$ buses to go from $lca$ to $u$. Let's learn how to calculate $a$ and $b$ fast. Firstly, notice that we can move down greedily. So we calculate $lowest[v]$ as the lowest vertex, where we can go from $v$ using only one bus. Secondly, notice that we can now build binary lifting on $lowest$. The answer is either $a + b$ or $a + b - 1$. Let's say the lowest vertex we can go from $v$ using $a - 1$ buses is $l_v$ and for $u$ and $b - 1$ buses it's $l_u$. $l_v$ and $l_u$ can be also calculated using binary lifting on $lowest$. Then, if there is a route connecting $l_v$ and $l_u$, the answer is $a + b - 1$ and it's $a + b$ otherwise. Let's calculate $l_v$ and $l_u$ for all the queries. Now we build an euler's tour. For each we now know the interval, corresponding to it's subtree. Let's say it is $[time\_in[v], time\_out[v])$. Then we run dfs again and do the following: when we came into $l_v$ we ask for sum on $[time\_in[l_u], time\_out[l_u])$. Now for each way, starting in $l_v$ we add $1$ to its other end. Now we run dfs for all of its children. And now we ask for sum on $[time\_in[l_u], time\_out[l_u])$ for the second time. If it changed the route connecting $l_v$ and $l_u$ exists. Asymptotics is $O(n \cdot log(n) + m \cdot log(n) + q \cdot log(n))$. Read the solution for better understanding. It tried to make it as readable as possible.
[ "binary search", "data structures", "trees" ]
2,800
#include <bits/stdc++.h> using namespace std; int run(); int main() { #ifdef home freopen("i", "r", stdin); freopen("d", "w", stderr); #endif cout.precision(15); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); run(); } const int N = 200000; const int logN = 19; int n; vector<int> graph[N]; int binary_lift_lca[N][logN]; int time_in[N]; int time_out[N]; int current_time; int height[N]; // Dfs to calculate all important things // Also generate Euler's tour void dfs_precalc_lca(int v, int ancestor = -1) { binary_lift_lca[v][0] = ancestor; height[v] = (ancestor != -1 ? height[ancestor] + 1 : 0); if (v < 0 || v >= N) { cerr << "Fuck!"; } time_in[v] = current_time++; for (int i = 1; i < logN; i++) { if (binary_lift_lca[v][i - 1] == -1) { binary_lift_lca[v][i] = -1; } else { binary_lift_lca[v][i] = binary_lift_lca[binary_lift_lca[v][i - 1]][i - 1]; } } for (auto to : graph[v]) { dfs_precalc_lca(to, v); } time_out[v] = current_time; } int lowest[N]; int dfs_precalc_lowest(int v) { for (auto to : graph[v]) { lowest[v] = min(lowest[v], dfs_precalc_lowest(to)); } return lowest[v]; } // Dfs to calculate lowest vertices we can get from current in 2 ** i turns int binary_lift_way[N][logN]; void dfs_precalc_binary_lift_way(int v) { binary_lift_way[v][0] = lowest[v]; for (int i = 1; i < logN; i++) { binary_lift_way[v][i] = binary_lift_way[binary_lift_way[v][i - 1]][i - 1]; } for (auto to : graph[v]) { dfs_precalc_binary_lift_way(to); } } // Check if v is ancestor of u bool isAncestor(int v, int u) { if (v == -1) { return true; } if (u == -1) { return false; } return time_in[v] <= time_in[u] && time_out[v] >= time_out[u]; } int lca(int v, int u) { if (isAncestor(v, u)) { return v; } if (isAncestor(u, v)) { return u; } for (int i = logN - 1; i >= 0; i--) { if (!isAncestor(binary_lift_lca[v][i], u)) { v = binary_lift_lca[v][i]; } } return binary_lift_lca[v][0]; } // Check if it's possible to get from v to u using routes bool reachable(int v, int u) { for (int i = logN - 1; i >= 0; i--) { if (!isAncestor(binary_lift_way[v][i], u)) { v = binary_lift_way[v][i]; } } v = binary_lift_way[v][0]; return isAncestor(v, u); } // We go up from v, using as little number of buses as possible, until we get to the vertex // From which we can get to u in one turn // Returns pair<int, int> --- penultimate vertex on the way and the number of buses we used pair<int, int> penultimate(int v, int u) { int cnt = 0; for (int i = logN - 1; i >= 0; i--) { if (!isAncestor(binary_lift_way[v][i], u)) { cnt += (1 << i); v = binary_lift_way[v][i]; } } return {v, cnt}; } // Here is just classical fenwick we'll use in dfs_calculate_answer int fenwick[N + 1]; int f(int a) { return a & (-a); } void fenwickAdd(int v, int val = 1) { v++; // Fenwick is 1 indexed, v is 0 indexed for (; v <= N; v += f(v)) { fenwick[v] += val; } } int fenwickGet(int r) { int ans = 0; for (; r > 0; r -= f(r)) { ans += fenwick[r]; } return ans; } int fenwickGet(int l, int r) { return fenwickGet(r) - fenwickGet(l); } int answer[N]; vector<pair<int, int>> query_for_vertex[N]; int cnt_on_segment[N]; vector<int> way_end[N]; void dfs_calculate_answer(int v) { for (auto query : query_for_vertex[v]) { int u, id; tie(u, id) = query; cnt_on_segment[id] -= fenwickGet(time_in[u], time_out[u]); } for (auto end : way_end[v]) { fenwickAdd(time_in[end]); } for (auto to : graph[v]) { dfs_calculate_answer(to); } // The same thing as at the beginning for (auto query : query_for_vertex[v]) { int u, id; tie(u, id) = query; cnt_on_segment[id] += fenwickGet(time_in[u], time_out[u]); // That means that exists the route, connecting v and u if (cnt_on_segment[id] > 0) { answer[id]--; // So our assuming is incorrect and we should decrease answer } } } pair<int, int> way[N]; bool bad[N]; int run() { cin >> n; for (int i = 1; i < n; i++) { int p; cin >> p; --p; graph[p].push_back(i); } int m; cin >> m; for (int i = 0; i < m; i++) { int v, u; cin >> v >> u; --v; --u; way_end[v].push_back(u); // We will know where routes starting in this vertex end way_end[u].push_back(v); // We'll need it in dfs_calculate_answer way[i] = {v, u}; } // Precalc lca, Euler's tour and heights dfs_precalc_lca(0); // For each vertex we store lowest possible vertex // In one turn // Initially it's just its height for (int i = 0; i < n; i++) { lowest[i] = i; } // Split way to vertical for (int i = 0; i < m; i++) { int v, u; tie(v, u) = way[i]; int lca_ = lca(v, u); if (height[lowest[v]] > height[lca_] ) { lowest[v] = lca_; } if (height[lowest[u]] > height[lca_]) { lowest[u] = lca_; } } dfs_precalc_lowest(0); // Now we precalc binary lifts to answer queries dfs_precalc_binary_lift_way(0); int q; cin >> q; for (int i = 0; i < q; i++) { int v, u; cin >> v >> u; --v; --u; int len_v, len_u; int lca_ = lca(v, u); if (!reachable(v, lca_) || !reachable(u, lca_)) { // It's impossible to get from vertex to lca bad[i] = true; } tie(v, len_v) = penultimate(v, lca_); tie(u, len_u) = penultimate(u, lca_); if (v != lca_ && u != lca_) { // Route isn't vertical query_for_vertex[v].push_back({u, i}); // Here we store query's second vertex and id } answer[i] = len_v + len_u; // We assume there is no direct route between v and u // Overwise we'll decrement it later if (v != lca_) { answer[i]++; } if (u != lca_) { answer[i]++; } } dfs_calculate_answer(0); for (int i = 0; i < q; i++) { cout << (bad[i] ? -1 : answer[i]) << '\n'; } }
984
A
Game
Two players play a game. Initially there are $n$ integers $a_1, a_2, \ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns. The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it. You want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.
First let's notice that the first player makes $\lceil \frac{n - 1}{2} \rceil$ turns and the second one makes $\lfloor \frac{n - 1}{2} \rfloor$. So, if numbers are $1$-indexed and sorted, first player can make the answer not more than $(n - \lceil \frac{n - 1}{2} \rceil)$-th by deleting maximal number every time. The second can make it not less than $(\lfloor \frac{n - 1}{2} \rfloor + 1)$-th. But $n - \lceil \frac{n - 1}{2} \rceil = \lfloor \frac{n - 1}{2} \rfloor + 1$, because $n - 1 = \lceil \frac{n - 1}{2} \rceil + \lfloor \frac{n - 1}{2} \rfloor$. So the answer has minimal and maximal values, which are the same. So the answer is $(\lfloor \frac{n - 1}{2} \rfloor + 1)$-th number ascending. Asymptotics is $O(n \cdot log(n)$ or $O(n^2)$
[ "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int a[1000]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n); cout << a[(n - 1) / 2]; }
984
B
Minesweeper
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it? He needs your help to check it. A Minesweeper field is a rectangle $n \times m$, where each cell is either empty, or contains a digit from $1$ to $8$, or a bomb. The field is valid if for each cell: - if there is a digit $k$ in the cell, then exactly $k$ neighboring cells have bombs. - if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $8$ neighboring cells).
Let's make two-dimensional array $d[n][m]$. For each cell $i,j$ if it has bomb in it we add $1$ in $d[g][h]$ where $g,h$ is neighboring cell for $i,j$. Now $d[i][j]$ is a number of bombs in neighboring cells of $i,j$ and we can check validity of field according to the condition of the problem: If there is a number $k$ in the cell, then exacly $k$ of neighboring cells have bombs. Otherwise, if cell has no bomb, then neighboring cells have no bombs.
[ "implementation" ]
1,100
#include <iostream> #include <vector> using std::vector; using std::cin; using std::cout; void setbomb(int x, int y, int n, int m, vector<vector<int>> &ans) { if (x > 0) { if (y > 0) ans[x - 1][y - 1]++; ans[x - 1][y]++; if (y < m - 1) ans[x - 1][y + 1]++; } if (x < n - 1) { if (y > 0) ans[x + 1][y - 1]++; ans[x + 1][y]++; if (y < m - 1) ans[x + 1][y + 1]++; } if (y > 0) ans[x][y - 1]++; if (y < m - 1) ans[x][y + 1]++; } int main(int argc, char *argv[]) { int n, m; cin >> n >> m; vector<vector<char>> v(n, vector<char>(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> v[i][j]; } } vector<vector<int>> ans(n, vector<int>(m)); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (v[i][j] == '*') setbomb(i, j, n, m, ans); } for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (v[i][j] == '.') { if (ans[i][j] != 0) { cout << "NO"; return 0; } } else if (v[i][j] != '*') if (ans[i][j] != v[i][j] - '0') { cout << "NO"; return 0; } } cout << "YES"; return 0; }