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
553
A
Kyoya and Colored Balls
Kyoya Ootori has a bag with $n$ colored balls that are colored with $k$ different colors. The colors are labeled from $1$ to $k$. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color $i$ before drawing the last ball of color $i + 1$ for all $i$ from $1$ to $k - 1$. Now he wonders how many different ways this can happen.
Let $f_{i}$ be the number of ways to solve the problem using only the first $i$ colors. We want to compute $f_{n}$. Initially, we have $f_{1} = 1$, since we only have a single color, and balls of the same color are indistinguishable. Now, to go from $f_{i}$ to $f_{i + 1}$, we note that we need to put at a ball of color $i + 1$ at the very end, but the other balls of color $i + 1$ can go anywhere in the sequence. The number of ways to arrange the balls of color $i + 1$ is $\binom{c}{\strut C_{1}+C_{2}\stackrel{+}{\downarrow}_{\star+}C_{i+1}-1}\Big\}$ (minus one because we need to put one ball at the very end). Using this recurrence, we can solve for $f_{n}$. Thus, we need to precompute binomial coefficients then evaluate the product.
[ "combinatorics", "dp", "math" ]
1,500
import java.io.*; import java.util.*; public class ColoredBalls { public static int mod = 1000000007; public static int MAXN = 1010; public static void main (String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out, true); long[][] comb = new long[MAXN][MAXN]; comb[0][0] = 1; for (int i = 1; i < MAXN; i++) { comb[i][0] = 1; for (int j = 1; j <= i; j++) { comb[i][j] = (comb[i-1][j] + comb[i-1][j-1]) % mod; } } int K = in.nextInt(); int[] color = new int[K]; for (int i = 0; i < K; i++) color[i] = in.nextInt(); long res = 1; int total = 0; for (int i = 0; i < K; i++) { res = (res * comb[total + color[i] - 1][color[i] - 1]) % mod; total += color[i]; } out.println(res); out.close(); System.exit(0); } }
553
B
Kyoya and Permutation
Let's define the permutation of length $n$ as an array $p = [p_{1}, p_{2}, ..., p_{n}]$ consisting of $n$ distinct integers from range from $1$ to $n$. We say that this permutation maps value $1$ into the value $p_{1}$, value $2$ into the value $p_{2}$ and so on. Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a sequence of numbers such that each element of this sequence is being mapped into the next element of this sequence (and the last element of the cycle is being mapped into the first element of the cycle). The cyclic representation is a representation of $p$ as a collection of cycles forming $p$. For example, permutation $p = [4, 1, 6, 2, 5, 3]$ has a cyclic representation that looks like $(142)(36)(5)$ because 1 is replaced by 4, 4 is replaced by 2, 2 is replaced by 1, 3 and 6 are swapped, and 5 remains in place. Permutation may have several cyclic representations, so Kyoya defines the standard cyclic representation of a permutation as follows. First, reorder the elements within each cycle so the largest element is first. Then, reorder all of the cycles so they are sorted by their first element. For our example above, the standard cyclic representation of $[4, 1, 6, 2, 5, 3]$ is $(421)(5)(63)$. Now, Kyoya notices that if we drop the parenthesis in the standard cyclic representation, we get another permutation! For instance, $[4, 1, 6, 2, 5, 3]$ will become $[4, 2, 1, 5, 6, 3]$. Kyoya notices that some permutations don't change after applying operation described above at all. He wrote all permutations of length $n$ that do not change in a list in lexicographic order. Unfortunately, his friend Tamaki Suoh lost this list. Kyoya wishes to reproduce the list and he needs your help. Given the integers $n$ and $k$, print the permutation that was $k$-th on Kyoya's list.
Solving this requires making the observation that only swaps between adjacent elements are allowed, and all of these swaps must be disjoint. This can be discovered by writing a brute force program, or just noticing the pattern for small $n$. Here's a proof for why this is. Consider the cycle that contains $n$. Since $n$ is the largest number, it must be the last cycle in the sequence, and it's the first element of the sequence. If this cycle is length 1, then we're obviously ok (we can always append $(n)$ to the end). If the cycle is of length 2, we need $n$ to be involved in a cycle with $n - 1$. Lastly, if the cycle is of length 3 or more, we will see we run into a problem. We'll only show this for a cycle of length 3 (though this argument does generalize to cycles of larger length). Let $(nxy)$ be the cycle. So that means, $n$ is replaced by $x$, $x$ is replaced by $y$ and $y$ is replaced by $n$. So, in other words, the original permutation involving this cycle must look like However, we need it to look like $(nxy)$ so this case is impossible. So, once we know that $n$ is a in a cycle of length $1$ or $2$, we can ignore the last 1 or 2 elements of the permutation and repeat our reasoning. Thus, the only valid cases are when we swap adjacent elements, and all swaps are disjoint. After making this observation, we can see the number of valid permutations of length n is fib(n+1). (to see this, write try writing a recurrence). To reconstruct the kth permutation in the list, we can do this recursively as follows: If k is less than fib(n), then $1$ must be the very first element, and append the $k$th permutation on {1,...,n-1} with 1 added everywhere. Otherwise, add $2, 1$ to the very front and append the k-fib(n)th permutation on {1,...,n-2} with 2 added everywhere.
[ "binary search", "combinatorics", "constructive algorithms", "greedy", "implementation", "math" ]
1,900
import java.io.PrintWriter; import java.util.Scanner; public class PermutationFinder { public static void main (String[] args) { Scanner in = new Scanner (System.in); PrintWriter out = new PrintWriter (System.out, true); int N = in.nextInt(); long K = in.nextLong(); long[] fib = new long[N+1]; fib[0] = fib[1] = 1; for (int i = 2; i <= N; i++) fib[i] = fib[i-1]+fib[i-2]; int idx = 0; int[] res = new int[N]; while (idx < N) { if (K <= fib[N-idx-1]) { res[idx] = idx+1; idx++; } else { K -= fib[N-idx-1]; res[idx] = idx+2; res[idx+1] = idx+1; idx += 2; } } for (int i = 0; i < N; i++) { if (i != 0) out.print(" "); out.print(res[i]); } out.println(); out.close(); System.exit(0); } }
553
C
Love Triangles
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has $n$ characters. The characters are labeled from $1$ to $n$. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of $m$ known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo $1 000 000 007$.
Let's look at the graph of characters who love each other. Each love-connected component can be collapsed into a single node, since we know that all characters in the same connected component must love each other. Now, we claim that the resulting collapsed graph with the hate edges has a solution if and only if the resulting graph is bipartite. To show this, suppose the graph is not bipartite. Then, there is an odd cycle. If the cycle is of length 1, it is a self edge, which clearly isn't allowed (since a node must love itself). For any odd cycle of length more than 1, let's label the nodes in the cycle $a_{1}, a_{2}, a_{3}, ..., a_{k}$. Then, in general, we must have $a_{i}$ loves $a_{(i + 2)}$, since $a_{i}, a_{(i + 1)}$ hate each other and $a_{(i + 1)}, a_{(i + 2)}$ hate each other (all indicies taken mod $k$). However, we can use the fact that the cycle is odd and eventually get that $a_{i}$ and $a_{i + 1}$ love each other. However, this is a contradiction, since we said they must originally hate each other. For the other direction, suppose the graph is bipartite. Let $X, Y$ be an arbitrary bipartition of the graph. If we let all nodes in $X$ love each other and all nodes in $Y$ love each other, and every edge between $X$ and $Y$ hate each other, then we get a solution. (details are omitted, though I can elaborate if needed). Thus, we can see that we have a solution if and only if the graph is bipartite. So, if the graph is not bipartite, the answer is zero. Otherwise, the second part of the proof gives us a way to count. We just need to count the number of different bipartitions of the graph. It's not too hard to see that this is just simply 2^(number of connected components - 1) (once you fix a node, you fix every node connected to it). This entire algorithm takes $O(N + M)$ time.
[ "dfs and similar", "dsu", "graphs" ]
2,200
import java.io.*; import java.util.*; public class OddGraphs { public static int mod = 1000000007; static class Edge { public int from, to; public Edge(int from, int to) { this.from = from; this.to = to; } } public static ArrayList<Integer>[] graph; public static ArrayList<Edge> zeros, ones; public static int[] par, size; public static int find(int x) { return x == par[x] ? x : (par[x] = find(par[x])); } public static void join(int a, int b) { int x = find(a), y = find(b); if (x == y) return; if (size[x] < size[y]) {int t = x; x = y; y = t;} par[y] = x; size[x] += size[y]; } public static void main (String[] args) { InputReader in = new InputReader (System.in); PrintWriter out = new PrintWriter (System.out, true); int N = in.nextInt(), M = in.nextInt(); zeros = new ArrayList<>(); ones = new ArrayList<>(); for (int i = 0; i < M; i++) { int a = in.nextInt()-1, b = in.nextInt()-1, c = in.nextInt(); if (c == 0) { zeros.add(new Edge(a,b)); } else { ones.add(new Edge(a,b)); } } par = new int[N]; size = new int[N]; for (int i = 0; i < N; i++) { par[i] = i; size[i] = 1; } for (Edge e : ones) { join(e.from, e.to); } graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<>(); for (Edge e : zeros) { graph[find(e.from)].add(find(e.to)); graph[find(e.to)].add(find(e.from)); } vis = new boolean[N]; color = new boolean[N]; int comp = 0; for (int i = 0; i < N; i++) { if (find(i) == i && !vis[i]) { if (!dfs(i, false)) { out.println(0); out.close(); System.exit(0); } else { comp++; } } } int res = 1; for (int i = 0; i < comp-1; i++) res = (res * 2) % mod; out.println(res); out.close(); System.exit(0); } public static boolean[] vis, color; public static boolean dfs(int node, boolean c) { if (vis[node]) return c == color[node]; vis[node] = true; color[node] = c; for (int neighbor : graph[node]) { if (!dfs(neighbor, !c)) return false; } return true; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
553
D
Nudist Beach
Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers. There are $n$ cities, labeled from 1 to $n$, and $m$ bidirectional roads between them. Currently, there are Life Fibers in every city. In addition, there are $k$ cities that are fortresses of the Life Fibers that cannot be captured under any circumstances. So, the Nudist Beach can capture an arbitrary non-empty subset of cities with no fortresses. After the operation, Nudist Beach will have to defend the captured cities from counterattack. If they capture a city and it is connected to many Life Fiber controlled cities, it will be easily defeated. So, Nudist Beach would like to capture a set of cities such that for each captured city the ratio of Nudist Beach controlled neighbors among all neighbors of that city is as high as possible. More formally, they would like to capture a non-empty set of cities $S$ with no fortresses of Life Fibers. The strength of a city $x\in S$ is defined as (number of neighbors of $x$ in $S$) / (total number of neighbors of $x$). Here, two cities are called neighbors if they are connnected with a road. The goal is to maximize the strength of the weakest city in $S$. Given a description of the graph, and the cities with fortresses, find a non-empty subset that maximizes the strength of the weakest city.
The algorithm idea works as follows: Start with all allowed nodes. Remove the node with the smallest ratio. Repeat. Take the best ratio over all iterations. It's only necessary to consider these subsets. Proof for why. We say this process finds a ratio of at least p if and only if there exists a subset with ratio at least p. Exists a subset with ratio at least p => algorithm will find answer of at least p. First, observe that the ratio of any particular node only decreases throughout the algorithm. Thus, all nodes in this subset initally have ratio at least p. Then, the very first node that gets removed from this subset must not have ratio smaller than p, thus the above algorithm will record an answer of at least p. Exists no subset with ratio at least p => algorithm finds answer at most p. No subset with ratio at least p implies every subset has ratio at most p. Thus, at every iteration of our algorithm, we'll get an answer of at most p, so we're done. Thus, we can see these are necessary and sufficient conditions, so we're done. Now for efficient implementation, we can use a variant of Dijkstra's. Recording the best subset must be done a bit more carefully as well.
[ "binary search", "graphs", "greedy" ]
2,300
import java.io.*; import java.util.*; public class GraphRatios { public static ArrayList<Integer>[] graph; public static int[] deg, cur; public static boolean[] vis; public static void main (String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out, true); int N = in.nextInt(), M = in.nextInt(), K = in.nextInt(); vis = new boolean[N]; for (int i = 0; i < K; i++) vis[in.nextInt()-1] = true; deg = new int[N]; cur = new int[N]; graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<>(); for (int i = 0; i < M; i++) { int a = in.nextInt()-1, b = in.nextInt()-1; graph[a].add(b); graph[b].add(a); deg[a]++; deg[b]++; if (vis[a]) cur[b]++; if (vis[b]) cur[a]++; } PriorityQueue<State> pq = new PriorityQueue<State>(); for (int i = 0; i < N; i++) if (!vis[i]) { pq.add (new State(i, cur[i])); } long num = 1, den = 1; int[] lst = new int[N]; int idx = 0; int best = 0; while (pq.size() > 0) { State s = pq.poll(); if (cur[s.node] != s.val || vis[s.node]) continue; lst[idx++] = s.node; long tn = s.val, td = deg[s.node]; if (num * td > den * tn) {num = tn; den = td; best = idx-1;} vis[s.node] = true; for (int neighbor : graph[s.node]) if (!vis[neighbor]) { pq.add(new State(neighbor, ++cur[neighbor])); } } int[] res = new int[idx-best]; for (int i = best; i < idx; i++) res[i-best] = lst[i]+1; // randomize order of output, just because I can. for (int i = 0; i < res.length; i++) { int j = (int)(Math.random() * (i+1)); if (j == i) continue; int t = res[i]; res[i] = res[j]; res[j] = t; } out.println(res.length); for (int i = 0; i < res.length; i++) { if (i != 0) out.print(" "); out.print(res[i]); } out.println(); out.close(); System.exit(0); } public static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class State implements Comparable<State> { public int node; public long val; public State(int node, int val) { this.node = node; this.val = val; } public int compareTo(State other) { return (int)(Math.signum(deg[node] * other.val - val * deg[other.node])); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
553
E
Kyoya and Train
Kyoya Ootori wants to take the train to get to school. There are $n$ train stations and $m$ one-way train lines going between various stations. Kyoya is currently at train station $1$, and the school is at station $n$. To take a train, he must pay for a ticket, and the train also takes a certain amount of time. However, the trains are not perfect and take random amounts of time to arrive at their destination. If Kyoya arrives at school strictly after $t$ time units, he will have to pay a fine of $x$. Each train line is described by a ticket price, and a probability distribution on the time the train takes. More formally, train line $i$ has ticket cost $c_{i}$, and a probability distribution $p_{i, k}$ which denotes the probability that this train will take $k$ time units for all $1 ≤ k ≤ t$. Amounts of time that each of the trains used by Kyouya takes are mutually independent random values (moreover, if Kyoya travels along the same train more than once, it is possible for the train to take different amounts of time and those amounts are also independent one from another). Kyoya wants to get to school by spending the least amount of money in expectation (for the ticket price plus possible fine for being late). Of course, Kyoya has an optimal plan for how to get to school, and every time he arrives at a train station, he may recalculate his plan based on how much time he has remaining. What is the expected cost that Kyoya will pay to get to school if he moves optimally?
The Naive solution is $O(MT^{2})$. Let $W_{j}(t)$ be the optimal expected time given we are at node $j$, with $t$ time units left. Also, let $W_{e}(t)$ be the optimal expected time given we use edge $e$ at time $t$. Now, we have $W_{j}(t)=\left\{\operatorname*{su}_{\mathrm{outest~distance~from~j~to~}}N+X\quad\mathrm{if~}t<=0\nonumber\\ {\operatorname*{lim_{ellerwise}~\ d i w e}(t)\quad}\quad\mathrm{otherwise}\ ,$ And, if e = (u->v), we have $W_{e}(t)=d i s t(e)+\sum_{k=1}^{T}P_{e}(k)W_{v}(t-k)$ Doing all this naively takes $O(MT^{2})$. Now, we'll speed this up using FFT. We'll focus on only a single edge for now. The problem here, however, is that not all $W_{v}$ values are given in advance. Namely, the $W_{v}$ values require us to compute the $W_{e}$ values for all edges at a particular time, and vice versa. So we need some sort of fast "online" version of FFT. We do this as follows. Let's abstract away the original problem, and let's say we're given two arrays a,b, where a is only revealed one at a time to us, and b is given up front, and we need to compute c, their convolution (in the original problem b is $P_{e}$, and a is $W_{v}$, and c is $W_{e}$). Now, when we get the ith value of a, we need to return the ith value of the convolution of c. We can only get the ith value of a when we compute the i-1th values of c for all c. Split up b into a block of size 1, a block of size 1, then a block of size 2, then a block of size 4, then 8, and so on. Now, we get $a_{0}$, which will allow us to compute $c_{1}$, which lets us get $a_{1}$, which allows us to compute $c_{2}$, and so on. So, now we have the following: We'll describe the processing of a single $a_{i}$ When we get $a_{i}$, we will first convolve it with the first two blocks, and add those to the appropriate entry. Now, suppose $a_{i}$ is multiple of a $2^{k}$ for some k. Then, we will convolve $a_{i - 2^{k}}$ .. $a_{i - 1}$ with the block in b with the same size. As an example. This gives us $c_{0}$, which then allows us to get $a_{1}$ This gives us $c_{1}$, which then allows us to get $a_{2}$ $a_{2}$ is now a power of 2, so this step will also additionally convolve $a_{0}, a_{1}$ with $b_{3}, b_{4}$ So, we can see this gives us $c_{2}$, which then allowus to get $a_{3}$, and so on and so forth. Thus, this process of breaking into blocks works. As for runtime, we run FFT on a block size of B T/B times, so this term contributes (T/B) * B log B = T log B So, we sum T log 2 + T log 4 + ... + T log 2\^(log T) <= T log\^2 T Thus, the overall time per edge is $T\log^{2}T$, which gives us a total runtime of $O(M T\log^{2}T)$.
[ "dp", "fft", "graphs", "math", "probabilities" ]
3,200
import java.io.*; import java.util.*; public class RandomPaths { public static int N, M, T, X; public static int[][] prob; public static Edge[] e; public static double[][] inp; public static double[][] outp; public static int K; public static double[][][][] tfd; public static double[][] re, im; public static void main (String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out, true); N = in.nextInt(); M = in.nextInt(); T = in.nextInt(); X = in.nextInt(); K = Integer.numberOfTrailingZeros(Integer.highestOneBit(T))+2; e = new Edge[M]; prob = new int[M][T+1]; inp = new double[M][]; outp = new double[M][]; tfd = new double[M][][][]; re = new double[K][]; im = new double[K][]; for (int i = 0; i < K; i++) { re[i] = new double[1<<i]; im[i] = new double[1<<i]; } int[][] dist = new int[N][N]; for (int i = 0; i < N; i++) {Arrays.fill(dist[i], 1 << 29); dist[i][i] = 0;} for (int i = 0; i < M; i++) { int a = in.nextInt()-1, b = in.nextInt()-1, c = in.nextInt(); e[i] = new Edge(a,b,c); dist[a][b] = Math.min(dist[a][b], c); for (int j = 1; j <= T; j++) prob[i][j] = in.nextInt(); } for (int k = 0; k < N; k++) for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); double[] res = new double[N]; for (int i = 0; i < N-1; i++) res[i] = dist[i][N-1] + X; res[N-1] = 0; initTable(); for (int i = 0; i < M; i++) init(i, dist[e[i].b][N-1] + X); for (int t = 1; t <= T; t++) { for (int i = 0; i < M; i++) set(i, t-1, res[e[i].b]); Arrays.fill(res, 1l << 60); res[N-1] = 0; for (int i = 0; i < M; i++) res[e[i].a] = Math.min(res[e[i].a], e[i].c + outp[i][t]); } out.printf("%.10f\n", res[0]); out.close(); System.exit(0); } public static double[][] cosTable, sinTable; public static void initTable() { int levels = 18; cosTable = new double[levels][]; sinTable = new double[levels][]; for (int j = 1; j < levels; j++) { int n = 1 << j; cosTable[j] = new double[n / 2]; sinTable[j] = new double[n / 2]; cosTable[j][0] = 1; sinTable[j][0] = 0; double qc = Math.cos(2 * Math.PI / n), qs = Math.sin(2 * Math.PI / n); for (int i = 1; i < n / 2; i++) { cosTable[j][i] = cosTable[j][i - 1] * qc - sinTable[j][i - 1] * qs; sinTable[j][i] = sinTable[j][i - 1] * qc + cosTable[j][i - 1] * qs; } } } public static void transform(double[] real, double[] imag) { int n = real.length; if (n <= 1) return; int levels = Integer.numberOfTrailingZeros(n); for (int i = 0; i < n; i++) { int j = Integer.reverse(i) >>> (32 - levels); if (j > i) { double temp = real[i]; real[i] = real[j]; real[j] = temp; temp = imag[i]; imag[i] = imag[j]; imag[j] = temp; } } for (int size = 2; size <= n; size *= 2) { int halfsize = size / 2; int tablestep = n / size; for (int i = 0; i < n; i += size) { for (int j = i, k = 0; j < i + halfsize; j++, k += tablestep) { double tpre = real[j + halfsize] * cosTable[levels][k] + imag[j + halfsize] * sinTable[levels][k]; double tpim = -real[j + halfsize] * sinTable[levels][k] + imag[j + halfsize] * cosTable[levels][k]; real[j + halfsize] = real[j] - tpre; imag[j + halfsize] = imag[j] - tpim; real[j] += tpre; imag[j] += tpim; } } } } public static void init(int index, double p) { inp[index] = new double[T+1]; outp[index] = new double[T+1]; for (int i = 0; i <= T; i++) inp[index][i] = prob[index][i] / 100000.; int s = 100000; for (int i = 0; i <= T; i++) { s -= prob[index][i]; outp[index][i] = s / 100000. * p; } tfd[index] = new double[K][2][]; for (int i = 2; i < K; i++) { int start = (1<<(i-1))+1; int end = (1<<i)+1; int len = 2*(end-start); tfd[index][i][0] = new double[len]; tfd[index][i][1] = new double[len]; System.arraycopy(inp[index], start, tfd[index][i][0], 0, Math.min(T + 1 - start, len/2)); transform(tfd[index][i][0], tfd[index][i][1]); } } public static void set(int index, int id, double x) { outp[index][id] = x; if (id+1 <= T) outp[index][id+1] += x * inp[index][1]; if (id+2 <= T) outp[index][id+2] += x * inp[index][2]; for (int i = 2; i < K; i++) { if ((((id+1) >> (i-2)) & 1) == 1) break; int start = id-(1<<(i-1))+1; int end = id+1; int len = 2*(end-start); Arrays.fill(re[i], 0); Arrays.fill(im[i], 0); System.arraycopy(outp[index], start, re[i], 0, len/2); transform(re[i], im[i]); for (int j = 0; j < len; j++) { double tre, tim; tre = tfd[index][i][0][j] * re[i][j] - tfd[index][i][1][j] * im[i][j]; tim = tfd[index][i][1][j] * re[i][j] + tfd[index][i][0][j] * im[i][j]; re[i][j] = tre; im[i][j] = tim; } transform(im[i], re[i]); for (int j = 0; id+j+2 <= T && j < len; j++) outp[index][id+j+2] += re[i][j] / len; } } static class Edge { public int a, b, c; public Edge(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
554
A
Kyoya and Photobooks
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has? Please help Haruhi solve this problem.
Solving this problem just requires us to simulate adding every character at every position at the string, and removing any duplicates. For instance, we can use a HashSet of Strings in Java to do this (a set in C++ or Python works as well).
[ "brute force", "math", "strings" ]
900
import java.util.HashSet; import java.util.Scanner; public class MissingLetter { public static void main (String[] args) { Scanner in = new Scanner (System.in); String s = in.next(); HashSet<String> hs = new HashSet<>(); for (int i = 0; i <= s.length(); i++) { for (char c = 'a'; c <= 'z'; c++) { hs.add(s.substring(0,i)+c+s.substring(i)); } } System.out.println(hs.size()); System.exit(0); } }
554
B
Ohana Cleans Up
Ohana Matsumae is trying to clean a room, which is divided up into an $n$ by $n$ grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column. Return the maximum number of rows that she can make completely clean.
For each row, there is only one set of columns we can sweep so it becomes completely clean. So, there are only $n$ configurations of sweeping columns to look at. Checking a configuration takes $O(n^{2})$ time to count the number of rows that are completely clean. There are $n$ configurations in all, so this takes $O(n^{3})$ time total. Alternatively, another way of solving this problem is finding the maximum number of rows that are all the same.
[ "brute force", "greedy", "strings" ]
1,200
import java.io.PrintWriter; import java.util.Scanner; public class LightMatrix { public static void main (String[] args) { Scanner in = new Scanner (System.in); PrintWriter out = new PrintWriter (System.out, true); int N = in.nextInt(); String[] board = new String[N]; for (int i = 0; i < N; i++) board[i] = in.next(); int res = 0; for (int i = 0; i < N; i++) { int count = 0; for (int j = 0; j < N; j++) if (board[j].equals(board[i])) count++; res = Math.max(res, count); } out.println(res); out.close(); System.exit(0); } }
555
A
Case of Matryoshkas
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art. The main exhibit is a construction of $n$ matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from $1$ to $n$. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, $1 → 2 → 4 → 5$. In one second, you can perform one of the two following operations: - Having a matryoshka $a$ that isn't nested in any other matryoshka and a matryoshka $b$, such that $b$ doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put $a$ in $b$; - Having a matryoshka $a$ directly contained in matryoshka $b$, such that $b$ is not nested in any other matryoshka, you may get $a$ out of $b$. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain ($1 → 2 → ... → n$). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.
Suppose we don't need to disassemble some sequence of dolls. Then no doll can be inserted into no doll from this chain. So we don't need to disassemble a sequence of dolls only if they are consecutive and start from $1$. Let the length of this chain be $l$. Then we will need to get one doll from another $n - k - l + 1$ times. Now we have a sequence $1 \rightarrow 2 \rightarrow ... \rightarrow l$ and all other dolls by themselves. $n - l + 1$ chains in total so we need to put one doll into another $n - l$ times. $2n - k - 2l + 1$ operations in total. Time: $O(n)$
[ "implementation" ]
1,500
null
555
B
Case of Fugitive
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of $n$ narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island $i$ has coordinates $[l_{i}, r_{i}]$, besides, $r_{i} < l_{i + 1}$ for $1 ≤ i ≤ n - 1$. To reach the goal, Andrewid needs to place a bridge between each pair of \textbf{adjacent} islands. A bridge of length $a$ can be placed between the $i$-th and the $(i + 1)$-th islads, if there are such coordinates of $x$ and $y$, that $l_{i} ≤ x ≤ r_{i}$, $l_{i + 1} ≤ y ≤ r_{i + 1}$ and $y - x = a$. The detective was supplied with $m$ bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
We can put a bridge between bridges $i$ and $i + 1$ if its length lies in the segment $[l_{i + 1} - r_{i};r_{i + 1} - l_{i}]$. Now we have a well-known problem: there are $n - 1$ segments and $m$ points on a plane, for every segment we need to assign a point which lies in it to this segment and every point can be assigned only once. Let's call a segment open if no point is assigned to it. Let's go through all points from left to right and at every moment keep all open segments that contain current point in a BST (std::set). When processing a point it should be assigned to the segment (from our set) that has the leftmost right end. This algorithm will find the answer if there is one. Suppose this solution is wrong and suppose there is a solution in which point $A$ is assigned to another open segment (there's no sense in skipping this point). Then some point $B$ is assigned to the segment which $A$ was assigned to. $B$ is to the right of $A$ so we can swap them and come to our answer again. Time: $O((n + m)log(n + m))$
[ "data structures", "greedy", "sortings" ]
2,000
null
555
C
Case of Chocolate
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom. A bar of chocolate can be presented as an $n × n$ table, where each cell represents one piece of chocolate. The columns of the table are numbered from $1$ to $n$ from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following $q$ actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge. After each action, he wants to know how many pieces he ate as a result of this action.
Let's solve this problem with two segment trees: we'll keep the lowest eaten piece for each column in one of them and the leftmost eaten piece for each row in another. Suppose we have a query $x$ $y$ $L$. Position where we'll stop eating chocolate is stored in the row segment tree so we can easily find the number of eaten pieces. After that we need to update both segment trees. $n$ is rather big in this problem. One way to deal with it is to use coordinate compression. Another is to use implicit segment trees. Time: $O(qlogq)$ or $O(qlogn)$
[ "data structures" ]
2,200
null
555
D
Case of a Top Secret
Andrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure. However, he needs help conducting one of the investigative experiment. There are $n$ pegs put on a plane, they are numbered from $1$ to $n$, the coordinates of the $i$-th of them are $(x_{i}, 0)$. Then, we tie to the bottom of one of the pegs a weight on a tight rope of length $l$ (thus, its coordinates will be equal to $(x_{i}, - l)$, where $i$ is the number of the used peg). Then the weight is pushed to the right, so that it starts to rotate counterclockwise. At the same time, if the weight during rotation touches some of the other pegs, it then begins to rotate around that peg. Suppose that each peg itself is very thin and does not affect the rope length while weight is rotating around it. More formally, if at some moment the segment of the rope contains one or more pegs in addition to the peg around which the weight is rotating, the weight will then rotate around the farthermost one of them on a shorter segment of a rope. In particular, if the segment of the rope touches some peg by its endpoint, it is considered that the weight starts to rotate around that peg on a segment of the rope of length $0$. At some moment the weight will begin to rotate around some peg, without affecting the rest of the pegs. Andrewid interested in determining the number of this peg. Andrewid prepared $m$ queries containing initial conditions for pushing the weight, help him to determine for each of them, around what peg the weight will eventually rotate.
I call the length of the part of the rope from the weight to the last met peg the active length (denoted as $L_{a}$). After each met peg active length is reduced. Let's process queries separately: at each step we can find next peg with using binary search. If active length becomes at least two times shorter or current step is the first one we proceed to the next step. Otherwise say current peg is peg $i$ and the next one is peg $j$ (without loss of generality $i < j$). Then after peg $j$ the rope will again touch peg $i$ and the weight will again rotate around peg $i$. Indeed, $2(x_{j} - x_{i}) \le L_{a}$ so the weight will rotate around a peg not to the right to peg $i$. And either $i = 1$ or $L_{a} \le x_{i} - x_{i - 1}$ so it won't also rotate around a peg to the left to peg $i$. As long as $L_{a} \ge x_{j} - x_{i}$ the weight will rotate around these two pegs so we can skip through several steps momentarily. This way active length is shortened at least twice so there will be no more than $logL$ steps. Time: $O(mlogLlogn)$
[ "binary search", "implementation", "math" ]
2,500
null
555
E
Case of Computer Network
Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network. In this network are $n$ vertices, some pairs of vertices are connected by $m$ undirected channels. It is planned to transfer $q$ important messages via this network, the $i$-th of which must be sent from vertex $s_{i}$ to vertex $d_{i}$ via one or more channels, perhaps through some intermediate vertices. To protect against attacks a special algorithm was developed. Unfortunately it can be applied only to the network containing directed channels. Therefore, as new channels can't be created, it was decided for each of the existing undirected channels to enable them to transmit data only in one of the two directions. Your task is to determine whether it is possible so to choose the direction for each channel so that each of the $q$ messages could be successfully transmitted.
First of all, let's reduce this problem to a problem on a tree. In order to achieve this let's orient edges in all biconnected components according to a DFS-order. We'll get a strongly connected component. Suppose it's false. Then this component can be divided into parts $A$ and $B$ such that there's no edge from $B$ to $A$. As initially there are at least two edges between $A$ and $B$ this situation is impossible because after entering $B$ in our DFS we'll have to exit via one of these edges. Contradiction. We can compress all biconnected components. Now we need to handle several queries "orient edges on a simple path in a tree" and to check if there are no conflicts. For this let's hang our tree and find LCA's for queries' pairs of vertices. Start another DFS and for every subtree count vertices in this subtree that are beginnings of queries' paths (call it $a$), that are ends of queries' paths (call it $b$) and that are precalculated LCAs (call it $c$). Now we can orient the edge connecting the root of the subtree and its parent: if $a - c$ is positive then it should be oriented up, if $b - c$ is positive then it should be oriented down, if both are positive there's no solution, if both are zeros the direction does not matter. Time: $O(n + ql_{q})$ where $l_{q}$ is the time of calculating LCA per query
[ "dfs and similar", "graphs", "trees" ]
2,800
null
556
A
Case of the Zeros and Ones
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length $n$ consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length $n - 2$ as a result. Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
If there still exist at least one $0$ and at least one $1$ in the string then there obviously exists either substring $01$ or substring $10$ (or both) and we can remove it. The order in which we remove substrings is unimportant: in any case we will make $min(#zeros, #ones)$ such operations. Thus the answer is $#ones + #zeros - 2min(#ones, #zeros) = |#ones - #zeros|$. Time: $O(n)$.
[ "greedy" ]
900
null
556
B
Case of Fake Numbers
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of $n$ similar gears. Each gear has $n$ teeth containing all numbers from $0$ to $n - 1$ in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on. Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if $n = 5$, and the active tooth is the one containing number $0$, then clockwise rotation makes the tooth with number $1$ active, or the counter-clockwise rotating makes the tooth number $4$ active. Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence $0, 1, 2, ..., n - 1$. Write a program that determines whether the given puzzle is real or fake.
Notice that after pressing the button $n$ times gears return to initial state. So the easiest solution is to simulate the process of pressing the button $n$ times and if at some step the active teeth sequence is $0, 1, ... , n - 1$ output "Yes" else "No". But this solution can be improved. For instance, knowing the active tooth of the first gear you can quickly determine how many times pressing the button is necessary, go to that state and check the sequence only once. Time: $O(n)$ or $O(n^{2})$
[ "brute force", "implementation" ]
1,100
null
557
A
Ilya and Diplomas
Soon a school Olympiad in Informatics will be held in Berland, $n$ schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the $n$ participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least $min_{1}$ and at most $max_{1}$ diplomas of the first degree, at least $min_{2}$ and at most $max_{2}$ diplomas of the second degree, and at least $min_{3}$ and at most $max_{3}$ diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all $n$ participants of the Olympiad will receive a diploma of some degree.
This problem can be solved in the different ways. We consider one of them - parsing cases. If $max_{1} + min_{2} + min_{3} \le n$ then the optimal solution is ($n - min_{2} - min_{3}$, $min_{2}$, $min_{3}$). Else if $max_{1} + max_{2} + min_{3} \le n$ then the optimal solution is ($max_{1}$, $n - max_{1} - min_{3}$, $min_{3}$). Else the optimal solution is ($max_{1}$, $max_{2}$, $n - max_{1} - max_{2}$). This solution is correct because of statement. It is guaranteed that $min_{1} + min_{2} + min_{3} \le n \le max_{1} + max_{2} + max_{3}$. Asymptotic behavior of this solution - O(1).
[ "greedy", "implementation", "math" ]
1,100
null
557
B
Pasha and Tea
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of $w$ milliliters and $2n$ tea cups, each cup is for one of Pasha's friends. The $i$-th cup can hold at most $a_{i}$ milliliters of water. It turned out that among Pasha's friends there are exactly $n$ boys and exactly $n$ girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: - Pasha can boil the teapot exactly once by pouring there at most $w$ milliliters of water; - Pasha pours the same amount of water to each girl; - Pasha pours the same amount of water to each boy; - if each girl gets $x$ milliliters of water, then each boy gets $2x$ milliliters of water. In the other words, each boy should get two times more water than each girl does. Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.
This problem can be solved in different ways too. We consider the simplest solution whici fits in the given restrictions. At first we sort all cups in non-decreasing order of their volumes. Due to reasons of greedy it is correct thatsorted cups with numbers from $1$ to $n$ will be given to girls and cups with numbers from $n + 1$ to $2 * n$ will be given to boys. Now we need to use binary search and iterate on volume of tea which will be poured for every girl. Let on current iteration $(lf + rg) / 2 = mid$. Then if for $i$ from $1$ to $n$ it is correct that $mid \le a_{i}$ and for $i$ from $n + 1$ to $2 * n$ it is correct that $2 * mid \le a_{i}$ then we need to make $lf = mid$. Else we need to make $rg = mid$. Asymptotic behavior of this solution - O($n * log(n)$) where $n$ - count of cups.
[ "constructive algorithms", "implementation", "math", "sortings" ]
1,500
null
557
C
Arthur and Table
Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable. In total the table Arthur bought has $n$ legs, the length of the $i$-th leg is $l_{i}$. Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number $d_{i}$ — the amount of energy that he spends to remove the $i$-th leg. A table with $k$ legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with $5$ legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths. Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.
This problem can be solved as follows. At first we need to sort all legs in non-descending order of their length. Also we need to use array $cnt[]$. Let iterate on length of legs (which will stand table) from the least. Let this lenght is equals to $maxlen$. Count of units of energy which we need for this we will store in variable $cur$. Obviously that we must unscrew all legs with lenght more than $maxlen$. For calculate count of units of energy for doing it we can use array with suffix sums, for exapmle. Then we add this value to $cur$. If count of legs with length $maxlen$ is not strictly greater than the number of the remaining legs then we need to unscrew some count of legs with length less than $maxlen$. For this we can use array $cnt[]$. In $cnt[i]$ we will store count of legs with difficulty of unscrew equals to $i$. In this array will store information about legs which already viewed. We will iterate on difficulty of unscrew from one and unscrew legs with this difficulties (and add this difficulties to variable $cur$) while count of legs with length $maxlen$ will not be strictly greater than the number of the remaining legs. When it happens we need to update answer with variable $cur$. Asymptotic behavior of this solution - O($n * d$), where $n$ - count of legs and $d$ - difference between maximal and minimal units of energy which needed to unscrew some legs.
[ "brute force", "data structures", "dp", "greedy", "math", "sortings" ]
1,900
null
557
D
Vitaly and Cycle
After Vitaly was expelled from the university, he became interested in the graph theory. Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once. Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of $n$ vertices and $m$ edges, not necessarily connected, without parallel edges and loops. You need to find $t$ — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find $w$ — the number of ways to add $t$ edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges. Two ways to add edges to the graph are considered equal if they have the same sets of added edges. Since Vitaly does not study at the university, he asked you to help him with this task.
To solve this problem we can use dfs which will check every connected component of graph on bipartite. It is clearly that count of edges which we need to add in graph to get the odd cycle is no more than three. Answer to this problem is three if count of edges in graph is zero. Then the number of ways to add three edges in graph to make odd cycle is equals to $n * (n - 1) * (n - 2) / 6$ where $n$ - count of vertices in graph. Answer to this problem is two if there is no connected component with number of vertices more than two. Then the number of ways to add two edges in graph to make odd cycle is equals to $m * (n - 2)$ where $m$ - number of edges in graph. Now we have one case when there is at least one connected component with number of vertices more than two. Now we need to use dfs and try to split every component in two part. If for some component we can't do it that means that graph already has odd cycle and we need to print $"0$ $1"$ and we can now finish our algorithm. If all connected components in graph are bipartite then we need to iterate on them. Let $cnt_{1}$ is the count of vertices in one part of current component and $cnt_{2}$ - count of vertices in the other part. If number of vertices in this component more than two we need to add to answer $cnt_{1} * (cnt_{1} - 1) / 2$ and $cnt_{2} * (cnt_{2} - 1) / 2$. Asymptotic behavior of this solution - O($n + m$), where $n$ - number of vertices in graph and $m$ - number of edges.
[ "combinatorics", "dfs and similar", "graphs", "math" ]
2,000
null
557
E
Ann and Half-Palindrome
Tomorrow Ann takes the hardest exam of programming where she should get an excellent mark. On the last theoretical class the teacher introduced the notion of a half-palindrome. String $t$ is a half-palindrome, if for all the odd positions $i$ ($1\leq i\leq{\frac{i|+1}{2}}$) the following condition is held: $t_{i} = t_{|t| - i + 1}$, where $|t|$ is the length of string $t$ if positions are indexed from $1$. For example, strings "abaa", "a", "bb", "abbbaa" are half-palindromes and strings "ab", "bba" and "aaabaa" are not. Ann knows that on the exam she will get string $s$, consisting only of letters a and b, and number $k$. To get an excellent mark she has to find the $k$-th in the lexicographical order string among all substrings of $s$ that are half-palyndromes. Note that each substring in this order is considered as many times as many times it occurs in $s$. The teachers guarantees that the given number $k$ doesn't exceed the number of substrings of the given string that are half-palindromes. Can you cope with this problem?
This problem can be solved with help of dynamic programming. At first we calculate matrix $good[][]$. In $good[i][j]$ we put $true$, if substring from position $i$ to position $j$ half-palindrome. Else we put in $good[i][j]false$. We can do it with iterating on "middle" of half-palindrome and expanding it to the left and to the right. There are $4$ cases of "middle" but we omit it because they are simple enough. Now we need to use Trie and we will put in it suffixes of given string. Also we will store array $cnt[]$. In $cnt[v]$ we will store number of half-palindromes which ends in vertex $v$ of our Trie. Let now we put in tree suffix which starts in position $i$, current symbol of string which we put is in position $j$ and we go in vertex $v$ of out Trie. Then if $good[i][j] = true$ we add one to $cnt[v]$. Now with help of dfs let calculate for every vertex $sum[v]$ - sum of numbers which stored in array $cnt[]$ for vertex $v$ and for vertices in all subtrees of vertex $v$. It is left only to restore answer. Start from root of our Trie. We will store answer in variable $ans$. In variable $k$ store number of required substring. Let now we in vertex $v$, by letter $'a'$ we can go in vertex $to_{a}$ and by letter $'b'$ - in vertex $to_{b}$. Then if $sum[to_{a}] \le k$ we make $ans + = 'a'$ and go in vertex $to_{a}$ of our Trie. Else we need to make as follows: $k$ - $= sum[to_{a}]$, $ans + = 'b'$ and go in vertex $to_{b}$ of our Trie. When $k$ will be $ \le 0$ print resulting string $ans$ and finish algorithm. Asymptotic behavior of this solution - O($szalph * n^{2}$) where $szalph$ - size of input alphabet (in this problem it equals to two) and $n$ - length of given string.
[ "data structures", "dp", "graphs", "string suffix structures", "strings", "trees" ]
2,300
null
558
A
Lala Land and Apple Trees
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere. Lala Land has exactly $n$ apple trees. Tree number $i$ is located in a position $x_{i}$ and has $a_{i}$ apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in $x = 0$ position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing. What is the maximum number of apples he can collect?
Let's divide all the trees into two different groups, trees with a positive position and trees with a negative position. Now There are mainly two cases: If the sizes of the two groups are equal. Then we can get all the apples no matter which direction we choose at first. If the size of one group is larger than the other. Then the optimal solution is to go to the direction of the group with the larger size. If the size of the group with the smaller size is $m$ then we can get apples from all the $m$ apple trees in it, and from the first $m + 1$ trees in the other group. So we can sort each group of trees by the absolute value of the trees position and calculate the answer as mentioned above. Time complexity: $O(n\ l o g\ n)$
[ "brute force", "implementation", "sortings" ]
1,100
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numeric>\n#include <cassert>\n#include <ctime>\n\n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807LL\n#define INF 2000000000\n#define PI acos(-1.0)\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_popcount(a)\n\nusing namespace std;\n\nvector<pair<int, int> > a, b;\n\nint main()\n{\n ios_base::sync_with_stdio(0);\n //freopen(\"lca.in\", \"r\", stdin);\n //freopen(\"lca.out\", \"w\", stdout);\n int n, x, y;\n cin >> n;\n for(int i=0;i<n;i++)\n {\n cin >> x >> y;\n if(x < 0) a.pb(mp(x, y));\n else b.pb(mp(x, y));\n }\n sort(a.begin(), a.end(), greater<pair<int, int> >());\n sort(b.begin(), b.end());\n int res = 0;\n if(a.size() == b.size())\n {\n for(int i=0;i<a.size();i++)\n res+=a[i].s + b[i].s;\n }\n else if(a.size() > b.size())\n {\n for(int i=0;i<b.size();i++)\n res+=a[i].s + b[i].s;\n res+=a[b.size()].s;\n }\n else\n {\n for(int i=0;i<a.size();i++)\n res+=a[i].s + b[i].s;\n res+=b[a.size()].s;\n }\n cout << res;\n return 0;\n}"
558
B
Amr and The Large Array
Amr has got a large array of size $n$. Amr doesn't like large arrays so he intends to make it smaller. Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array. Help Amr by choosing the smallest subsegment possible.
First observation in this problem is that if the subarray chosen has $x$ as a value that has the maximum number of occurrences among other elements, then the subarray should be $[x, ..., x]$. Because if the subarray begins or ends with another element we can delete it and make the subarray smaller. So, Let's save for every distinct element $x$ in the array three numbers, the smallest index $i$ such that $a_{i} = x$, the largest index $j$ such that $a_{j} = x$ and the number of times it appears in the array. And between all the elements that has maximum number of occurrences we want to minimize $j - i + 1$ (i.e. the size of the subarray). Time complexity: $O(n)$
[ "implementation" ]
1,300
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numeric>\n#include <cassert>\n#include <ctime>\n\n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807LL\n#define INF 2000000000\n#define PI acos(-1.0)\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_popcount(a)\n\nusing namespace std;\n\nint m[1000005], L[1000005];\n\nint main()\n{\n //ios_base::sync_with_stdio(0);\n //freopen(\"lca.in\", \"r\", stdin);\n //freopen(\"lca.out\", \"w\", stdout);\n int n, x, maxi = 0, mini = INF, ch = -1;\n scanf(\"%d\", &n);\n for(int i=0;i<n;i++)\n {\n scanf(\"%d\", &x);\n if(m[x] == 0)\n {\n L[x] = i;\n m[x] = 1;\n }\n else m[x]++;\n if(m[x] > maxi)\n {\n maxi = m[x];\n mini = i - L[x] + 1;\n ch = L[x] + 1;\n }\n else if(m[x] == maxi && i - L[x] + 1 < mini)\n {\n mini = i - L[x] + 1;\n ch = L[x] + 1;\n }\n }\n cout << ch << \" \" << ch + mini - 1;\n return 0;\n}"
558
C
Amr and Chemistry
Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment. Amr has $n$ different types of chemicals. Each chemical $i$ has an initial volume of $a_{i}$ liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal. To do this, Amr can do two different kind of operations. - Choose some chemical $i$ and double its current volume so the new volume will be $2a_{i}$ - Choose some chemical $i$ and divide its volume by two (integer division) so the new volume will be $\textstyle{\left|{\frac{a_{i}}{2}}\right\rangle}$ Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?
Let the maximum number in the array be $max$. Clearly, changing the elements of the array to any element larger than $max$ won't be optimal, because the last operation is for sure multiplying all the elements of the array by two. And not doing this operation is of course a better answer. Now we want to count the maximum number of distinct elements that can be reached from some element $a_{i}$ that are not larger than $max$. Consider an element $a_{i}$ that has a zero in the first bit of its binary representation. If we divided the number by two and the multiplied it by two we will get the original number again. But if it has a one, the resulting number will be different. So, for counting the maximum number of distinct elements we will assume $a_{i} = x$ where $x$ has only ones in its binary representation. From $x$ we can only reach elements that have a prefix of ones in its binary representation, and the other bits zeros (e.g. ${0, 1, 10, 11, 100, 110, 111, 1000, ...}$ ). Let's assume $max$ has $m$ bits in its binary representation, then $x$ can reach exactly ${\frac{m*(m+1)}{2}}\ +\ 1$ distinct elements. So, from each element in the array $a_{i}$ we can reach at most ${\frac{m*(m+1)}{2}}\ +\ 1$ elements. So, Let's generate the numbers that can be reached from each element $a_{i}$ using bfs to get minimum number of operations. And between all the numbers that are reachable from all the $n$ elements let's minimize the total number of operations. Time complexity: $O(n*m^{2}+m a x)$
[ "brute force", "graphs", "greedy", "math", "shortest paths" ]
1,900
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numeric>\n#include <cassert>\n#include <ctime>\n\n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807LL\n#define INF 2000000000\n#define PI acos(-1.0)\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_popcount(a)\n\nusing namespace std;\n\nint cnt[100005], vis[100005], steps[100005];\n\nint main()\n{\n //ios_base::sync_with_stdio(0);\n //freopen(\"lca.in\", \"r\", stdin);\n //freopen(\"lca.out\", \"w\", stdout);\n int n, res = INF, x, y;\n scanf(\"%d\", &n);\n for(int i=1;i<=n;i++)\n {\n scanf(\"%d\", &x);\n queue<pair<int, int> > q;\n q.push(mp(x, 0));\n while(!q.empty())\n {\n x = q.front().f;\n y = q.front().s;\n q.pop();\n if(x > 100003) continue;\n if(vis[x] == i) continue;\n vis[x] = i;\n steps[x]+=y;\n cnt[x]++;\n q.push(mp(x * 2, y + 1));\n q.push(mp(x / 2, y + 1));\n }\n }\n for(int i=0;i<=100000;i++)\n if(cnt[i] == n)\n if(res > steps[i])\n res = steps[i];\n printf(\"%d\", res);\n return 0;\n}"
558
D
Guess Your Way Out! II
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height $h$. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the nodes of the tree such that - The root is number $1$ - Each internal node $i$ ($i ≤ 2^{h - 1} - 1$) will have a left child with index = $2i$ and a right child with index = $2i + 1$ The level of a node is defined as $1$ for a root, or $1$ + level of parent of the node otherwise. The vertices of the level $h$ are called leaves. The exit to the maze is located at some leaf node $n$, the player doesn't know where the exit is so he has to guess his way out! In the new version of the game the player is allowed to ask questions on the format "Does the $ancestor(exit, i)$ node number belong to the range $[L, R]$?". Here $ancestor(v, i)$ is the ancestor of a node $v$ that located in the level $i$. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!. Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
First, each query in the level $i$ from $L$ to $R$ can be transmitted into level $i + 1$ from $L * 2$ to $R * 2 + 1$, so, we can transform each query to the last level. Let's maintain a set of correct ranges such that the answer is contained in one of them. At the beginning we will assume that the answer is in the range $[2^{h - 1}, 2^{h} - 1]$ inclusive. Now Let's process the queries. If the query's answer is yes, then we want to get the intersection of this query's range with the current set of correct ranges, and update the set with the resulting set. If the query's answer is no, we want to exclude the query's range from the current set of correct ranges, and update the set with the resulting set. After we finish processing the queries, if the set of correct ranges is empty, then clearly the game cheated. Else if the set has only one correct range $[L, R]$ such that $L = R$ then we've got an answer. Otherwise there are multiple exit candidates and the answer can't be determined uniquely using the current data. We will have to use stl::set data structure to make updating the ranges faster. In each yes query we delete zero or more ranges. In each no query we may add one range if we split a correct range, so worst case will be linear in queries count. Time complexity: $O(h\ast q+q\;l o g\ q)$
[ "data structures", "implementation", "sortings" ]
2,300
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numeric>\n#include <cassert>\n#include <ctime>\n\n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807LL\n#define INF 2000000000\n#define PI acos(-1.0)\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_popcount(a)\n\nusing namespace std;\n\nset<pair<LL, LL> > s;\nbool test;\n\nvoid solve(LL &xx, LL &yy, bool yes)\n{\n set<pair<LL, LL> >::iterator it = s.lower_bound(mp(xx, xx));\n set<pair<LL, LL> >::iterator it2 = s.lower_bound(mp(yy, yy));\n if(it == s.end())\n it--;\n if(it2 == s.end())\n it2--;\n pair<LL, LL> L = *it, R = *it2;\n if(yes)\n {\n if(R.s < xx)\n {\n test = false;\n return;\n }\n if(L.f > yy && it == s.begin())\n {\n test = false;\n return;\n }\n if(L.f > xx && it == s.begin())\n {\n if(R.f > yy)\n {\n it2--;\n R = *it2;\n }\n L = mp(R.f, min(yy, R.s));\n it = it2;\n while(it2 != s.end())\n {\n it++;\n s.erase(it2);\n it2 = it;\n }\n s.insert(L);\n }\n else\n {\n if(R.f > yy)\n {\n it2--;\n R = *it2;\n }\n if(L.f > xx)\n {\n it--;\n L = *it;\n }\n if(L.s < xx)\n {\n if(it == it2)\n {\n test = false;\n return;\n }\n it++;\n L = *it;\n }\n if(it == it2)\n {\n L = mp(max(xx, L.f), min(yy, R.s));\n s.clear();\n s.insert(L);\n return;\n }\n L = mp(max(xx, L.f), L.s);\n R = mp(R.f, min(yy, R.s));\n set<pair<LL, LL> >::iterator it3 = it, it4;\n it4 = it3;\n while(1)\n {\n if(it3 == it)\n {\n s.erase(it);\n break;\n }\n it4++;\n s.erase(it3);\n it3 = it4;\n }\n it3 = it2;\n it4 = it3;\n while(it3 != s.end())\n {\n it4++;\n s.erase(it3);\n it3 = it4;\n }\n s.insert(L);\n s.insert(R);\n }\n }\n else\n {\n if(R.s < xx)\n return;\n if(L.f > yy && it == s.begin())\n return;\n if(L.f > xx && it == s.begin())\n {\n if(R.f > yy)\n {\n it2--;\n R = *it2;\n }\n L = mp(yy + 1, R.s);\n it = it2;\n while(1)\n {\n if(it2 == s.begin())\n {\n s.erase(it2);\n break;\n }\n it--;\n s.erase(it2);\n it2 = it;\n }\n if(L.f <= L.s)\n s.insert(L);\n }\n else\n {\n if(R.f > yy)\n {\n it2--;\n R = *it2;\n }\n if(L.f > xx)\n {\n it--;\n L = *it;\n }\n if(L.s < xx)\n {\n if(it == it2) return;\n it++;\n L = *it;\n }\n bool can = true;\n if(it == it2)\n {\n s.erase(it);\n can = false;\n }\n L = mp(L.f, xx - 1);\n R = mp(yy + 1, R.s);\n set<pair<LL, LL> >::iterator it3 = it;\n while(can)\n {\n if(it == it2)\n {\n s.erase(it);\n break;\n }\n it3++;\n s.erase(it);\n it = it3;\n }\n if(L.f <= L.s)\n s.insert(L);\n if(R.f <= R.s)\n s.insert(R);\n }\n test &= (s.size() != 0);\n }\n}\n\nint main()\n{\n //ios_base::sync_with_stdio(0);\n //freopen(\"lca.in\", \"r\", stdin);\n //freopen(\"lca.out\", \"w\", stdout);\n int n, q, lev;\n LL x, y;\n int yes;\n scanf(\"%d %d\", &n, &q);\n s.insert(mp(1LL << (n - 1), (1LL << n) - 1));\n test = true;\n while(q-- && test)\n {\n scanf(\"%d %I64d %I64d %d\", &lev, &x, &y, &yes);\n for(int i=lev;i<n && test;i++)\n {\n x = x * 2;\n y = y * 2 + 1;\n }\n solve(x, y, yes);\n }\n if(!test)\n cout << \"Game cheated!\";\n else\n {\n pair<LL, LL> res;\n if(s.size() == 1)\n {\n res = *s.lower_bound(mp(0, 0));\n if(res.f != res.s) test = false;\n }\n else test = false;\n if(!test)\n cout << \"Data not sufficient!\";\n else cout << res.f;\n }\n return 0;\n}"
558
E
A Simple Task
This task is very simple. Given a string $S$ of length $n$ and $q$ queries each query is on the format $i$ $j$ $k$ which means sort the substring consisting of the characters from $i$ to $j$ in non-decreasing order if $k = 1$ or in non-increasing order if $k = 0$. Output the final string after applying the queries.
In this problem we will be using counting sort. So for each query we will count the number of occurrences for each character, and then update the range like this But this is too slow. We want a data structure that can support the above operations in appropriate time. Let's make 26 segment trees each one for each character. Now for each query let's get the count of every character in the range, and then arrange them and update each segment tree with the new values. We will have to use lazy propagation technique for updating ranges. Time complexity: $O(s z*q*\;l o g\;n)$ where sz is the size of the alphabet (i.e. = 26).
[ "data structures", "sortings", "strings" ]
2,300
"#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <utility>\n#include <iomanip>\n#include <set>\n#include <numeric>\n#include <cassert>\n#include <ctime>\n\n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807LL\n#define INF 2000000000\n#define PI acos(-1.0)\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_popcount(a)\n\nusing namespace std;\n\nint tree[400005][27], lazy[400005][27];\nchar s[100005];\n\nvoid build(int i,int L,int R)\n{\n if(L == R)\n {\n tree[i][s[L] - 'a'] = 1;\n for(int j=0;j<26;j++)\n lazy[i][j] = -1;\n return ;\n }\n build(i*2 + 1, L, (L + R) / 2);\n build(i*2 + 2, (L + R) / 2 + 1, R);\n for(int j=0;j<26;j++)\n {\n lazy[i][j] = -1;\n tree[i][j] = tree[i*2 + 1][j] + tree[i*2 + 2][j];\n }\n}\n\nvoid update(int i, int L, int R, int x, int y, int val, int j)\n{\n if(lazy[i][j] != -1)\n {\n tree[i][j] = lazy[i][j] * (R - L + 1);\n if(L != R)\n {\n lazy[i*2+1][j] = lazy[i][j];\n lazy[i*2+2][j] = lazy[i][j];\n }\n lazy[i][j] = -1;\n }\n if(L >= x && R <= y)\n {\n lazy[i][j] = val;\n tree[i][j] = lazy[i][j] * (R - L + 1);\n if(L != R)\n {\n lazy[i*2+1][j] = lazy[i][j];\n lazy[i*2+2][j] = lazy[i][j];\n }\n lazy[i][j] = -1;\n return;\n }\n if(L > y || R < x)\n return;\n update(i*2 + 1, L, (L + R) / 2, x, y, val, j);\n update(i*2 + 2, (L + R) / 2 + 1, R, x, y, val, j);\n tree[i][j] = tree[i*2 + 1][j] + tree[i*2 + 2][j];\n}\n\nint query(int i, int L, int R, int x, int y, int j)\n{\n if(lazy[i][j] != -1)\n {\n tree[i][j] = lazy[i][j] * (R - L + 1);\n if(L != R)\n {\n lazy[i*2+1][j] = lazy[i][j];\n lazy[i*2+2][j] = lazy[i][j];\n }\n lazy[i][j] = -1;\n }\n if(L >= x && R <= y)\n return tree[i][j];\n if(L > y || R < x)\n return 0;\n return query(i*2 + 1, L, (L + R) / 2, x, y, j) + query(i*2 + 2, (L + R) / 2 + 1, R, x, y, j);\n}\n\nvoid get(int i, int L, int R, int j)\n{\n if(lazy[i][j] != -1)\n {\n tree[i][j] = lazy[i][j] * (R - L + 1);\n if(L != R)\n {\n lazy[i*2+1][j] = lazy[i][j];\n lazy[i*2+2][j] = lazy[i][j];\n }\n lazy[i][j] = -1;\n }\n if(!tree[i][j])\n return ;\n if(L == R)\n {\n s[L] = j + 'a';\n return;\n }\n get(i*2 + 1, L, (L + R) / 2, j);\n get(i*2 + 2, (L + R) / 2 + 1, R, j);\n}\n\nint cnt[26];\n\nint main()\n{\n //ios_base::sync_with_stdio(0);\n //freopen(\"test0.txt\", \"r\", stdin);\n //freopen(\"lca.out\", \"w\", stdout);\n int n, q, x, y, up;\n scanf(\"%d %d\", &n, &q);\n scanf(\"%s\", s);\n build(0, 0, n - 1);\n for(int i=0;i<q;i++)\n {\n scanf(\"%d %d %d\", &x, &y, &up);\n x--, y--;\n for(int j=0;j<26;j++)\n cnt[j] = query(0, 0, n - 1, x, y, j);\n int curr = x;\n if(!up) curr = y;\n for(int j=0;j<26;j++)\n {\n if(!cnt[j]) continue;\n update(0, 0, n - 1, x, y, 0, j);\n if(up)\n {\n update(0, 0, n - 1, curr, curr + cnt[j] - 1, 1, j);\n curr+=cnt[j];\n }\n else\n {\n update(0, 0, n - 1, curr - cnt[j] + 1, curr, 1, j);\n curr-=cnt[j];\n }\n }\n }\n for(int i=0;i<26;i++)\n get(0, 0, n - 1, i);\n printf(\"%s\", s);\n return 0;\n}"
559
A
Gerald's Hexagon
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to $120^{\circ}$. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it. He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.
Let's consider regular triangle with sides of $k$ Let's split it to regular triangles with sides of $1$ by lines parallel to the sides. Big triange area $k^{2}$ times larger then small triangles area and therefore big triangle have splitted by $k^{2}$ small triangles. If we join regular triangles to sides $a_{1}, a_{3}$ and $a_{5}$ of hexagon we get a triangle sides of $a_{1} + a_{2} + a_{3}$. Then hexagon area is equals to $(a_{1} + a_{2} + a_{3})^{2} - a_{1}^{2} - a_{3}^{2} - a_{5}^{2}$.
[ "brute force", "geometry", "math" ]
1,600
null
559
B
Equivalent Strings
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings $a$ and $b$ of equal length are called equivalent in one of the two cases: - They are equal. - If we split string $a$ into two halves of the same size $a_{1}$ and $a_{2}$, and string $b$ into two halves of the same size $b_{1}$ and $b_{2}$, then one of the following is correct: - $a_{1}$ is equivalent to $b_{1}$, and $a_{2}$ is equivalent to $b_{2}$ - $a_{1}$ is equivalent to $b_{2}$, and $a_{2}$ is equivalent to $b_{1}$ As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent. Gerald has already completed this home task. Now it's your turn!
Let us note that "equivalence" described in the statements is actually equivalence relation, it is reflexively, simmetrically and transitive. It is meant that set of all string is splits to equivalence classes. Let's find lexicographic minimal strings what is equivalent to first and to second given string. And then check if its are equals. It is remain find the lexicographic minimal strings what is equivalent to given. For instance we can do it such a way: Every recursive call time works is $O(n)$ (where $n$ is length of strings) and string splitten by two twice smaller strings. Therefore time of work this function is $O(n\log(n))$, where $n$ is length of strings.
[ "divide and conquer", "hashing", "sortings", "strings" ]
1,700
String smallest(String s) { if (s.length() % 2 == 1) return s; String s1 = smallest(s.substring(0, s.length()/2)); String s2 = smallest(s.substring(s.length()/2), s.length()); if (s1 < s2) return s1 + s2; else return s2 + s1; }
559
C
Gerald and Giant Chess
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an $h × w$ field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Let's denote black cells ad $A_{0}, A_{1}, ..., A_{k - 1}$ . First of all, we have to sort black cells in increasing order of (row, column). If cell $x$ available from cell $y$, $x$ stands after $y$ in this order. Let $A_{k} = (h, w)$. Now we have to find number of paths from $(1, 1)$ to $A_{k}$ avoiding $A_{0}, ..., A_{k - 1}$. Let $D_{i}$ is number of paths from $(1, 1)$ to $A_{i}$ avoiding $A_{0}, ..., A_{i - 1}$. It's easy to see that $D_{k}$ is answer for the problem. Number of all paths from $(1, 1)$ to $(x_{i}, y_{i})$ is $C_{x_{i}+y_{i}-2}^{x_{i}-1}$. We should subtract from that value all paths containing at least one of previous black cells. We should enumerate first black cell on the path. It could be one of previous cell that is not below or righter than $A_{i}$. For each such cell $A_{j}$ we have to subtract number of paths from $(1, 1)$ to $A_{j}$ avoiding black cells multiplied by number of all paths from $A_{j}$ to $A_{i}$. We have to calculate factorials of numbers from $1$ to $2 \cdot 10^{5}$ and inverse elements of them modulo $10^{9} + 7$ for calculating binomial coefficients.
[ "combinatorics", "dp", "math", "number theory" ]
2,200
null
559
D
Randomizer
Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows. A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a \textbf{basic polygon}. If you shake a Randomizer, it draws some nondegenerate (i.e. having a non-zero area) convex polygon with vertices at some vertices of the \textbf{basic polygon}. The result of the roll (more precisely, the result of the shaking) is considered to be the number of points with integer coordinates, which were strictly inside (the points on the border are not considered) the selected polygon. Now Gerald is wondering: what is the expected result of shaking the Randomizer? During the shaking the Randomizer considers all the possible non-degenerate convex polygons with vertices at the vertices of the \textbf{basic polygon}. Let's assume that there are $k$ versions of the polygons. Then the Randomizer chooses each of them with probability $\frac{1}{k}$.
We can use Pick's theorem for calculate integer points number in every polygon. Integer points number on the segment between points $(0, 0)$ and $(a, b)$ one can calculate over $GCD(a, b)$. Integer points number in some choosen polynom is integer points number in basic polynom minus integer points number in segmnent of basic polynom separated by every segment of choosen polynom. Let consider every potencial segment of polygon. We can calculate integer points number in his segment and probability that we will meet it in choosen polygon. Probability of segment $A_{i}A_{i + k}$ is $\frac{2^{n-k-1}-1}{2^{n}-1-n-\frac{n(n-1)}{2}}$. Let use note that we can calculate only segments with $k < 60$ because of other segmnet propapility is too small.
[ "combinatorics", "geometry", "probabilities" ]
2,800
null
559
E
Gerald and Path
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight. The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument. You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
Lighted part of walking trail is union of ligted intervals. Let's sort spotlights in increasing order of $a_{i}$. Consider some lighted interval $(a, b)$. It's lighted by spotlights with numbers ${l, l + 1, ..., r}$ for some $l$ and $r$ ("substring" of spotlights). Let $x_{0}, ..., x_{k}$ is all possible boundaries of lighted intervals (numbers $a_{i} - l_{i}$, $a_{i}$ and $a_{i} + l_{i}$). Imagine, that we know possible lighted intervals of all substrings of spotlights. Let $left[l][r][j]$ is least possible $i$ such that set of spotlights with numbers ${l, l + 1, ..., r}$ lighting $[x_{i}, x_{j}]$. With $left$ we can calculate value $best[R][i]$ maximum possible length of walking trail that could be lighted using first $L$ spotlights in such way that $x_{i}$ is rightmost lighted point. It's easy to do in $O(n^{4})$ because $b e s t[R][i]=\operatorname*{max}_{l e f t\vert i+1\vert|R\vert|i\rangle,t}b e s t[l][t]+x_{i}-x_{l e f t\vert i+1\vert|R\vert|i\vert}$. Now all we have to do is calculate $left$. Consider some substring of spotlights $[l, r]$. Let all spotlights in the substring oriented in some way lighting some set of points. We could consider most left ($i$) and most right ($j$) lighted points, and left bound of first lighted interval ($t$). If set of lighted points is interval $t = j$. Consider how all the values change when we add spotlight $r + 1$ and choose its orientation. We have new lighted interval $[a, b]$ which is equal to $[a_{i} - l_{i}, a_{i}]$ or $[a_{i}, a_{i} + l_{i}]$. Now most left lighted point is $min(a, x_{i})$, most right is $max(b, x_{j})$. Right bound of leftmost lighted interval does not changes if $a > t$ or becomes equal to $b$, if $a \le t$. Not for each $L$ we can calculate $dp[r][j][y]$ least possible $i$ that it's possible to orient spotlights from $[L, r]$ in such way that $x_{i}$ is most left lighted point $x_{j}$ is most right one and right bound of leftmost lighted interval is $x_{t}$. Thet it's easy to calculate $left[L][][]$. That part is done in $O(n^{4})$ too. +97 Sammarize 10 years ago 166
[ "dp", "sortings" ]
3,000
null
560
A
Currency System in Geraldion
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
If there is a banlnot of value 1 then one can to express every sum of money. Otherwise one can't to express 1 and it is minimum unfortunate sum.
[ "implementation", "sortings" ]
1,000
null
560
B
Gerald is into Art
Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an $a_{1} × b_{1}$ rectangle, the paintings have shape of a $a_{2} × b_{2}$ and $a_{3} × b_{3}$ rectangles. Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?
It is easy to see that one can snuggle paintings to each other and to edge of board. For instance one can put one of painting right over other. Then height of two paintings equals to sum of two heights and width of two paintings is equals to maximum of two widths. Now we can just iterate orientation of paintings and board.
[ "constructive algorithms", "implementation" ]
1,200
null
566
A
Matching Names
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names. There are $n$ students in a summer school. Teachers chose exactly $n$ pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym $b$ to a student with name $a$ as the length of the largest common prefix $a$ and $b$. We will represent such value as $\operatorname{lcp}(a,b)$. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students. Find the matching between students and pseudonyms with the maximum quality.
Form a trie from all names and pseudonyms. Mark with red all vertices corresponding to names, and with blue all vertices corresponding to the pseudonyms (a single vertex may be marked several times, possibly with different colors). Note that if we match a name $a$ and a pseudonym $b$, then the quality of such match is $lcp(a, b) = 1 / 2(2 * lcp(a, b)) = 1 / 2(|a| + |b| - (|a| - lcp(a, b)) - (|b| - lcp(a, b)))$, that is equal to a constant $1 / 2(|a| + |b|)$, with subtracted half of a length of a path between $a$ and $b$ over the trie. So, what we need is to connect all red vertices with blue vertices with paths of a minimum possible total length. This can be done with a following greedy procedure: if we have a vertex $v$ with $x$ red vertices and $y$ blue vertices in its subtree then we must match $min(x, y)$ red vertices of its subtree to $min(x, y)$ blue vertices of its subtree and leave the remaining $max(x, y) - min(x, y)$ ref or blue vertices to the level higher. The correctness of such algorithm may be easily shown by the next idea. Give each edge of each path a direction from a red vertex to a blue. If some edge recieves two different directions after this procedure, we may cross-change two paths through it so that their total length is reduced by two. So, we get a solution in $O(sumlen)$ where $sumlen$ is a total length of all names and pseudonyms.
[ "dfs and similar", "strings", "trees" ]
2,300
null
566
B
Replicating Processes
A Large Software Company develops its own social network. Analysts have found that during the holidays, major sporting events and other significant events users begin to enter the network more frequently, resulting in great load increase on the infrastructure. As part of this task, we assume that the social network is $4n$ processes running on the $n$ servers. All servers are absolutely identical machines, each of which has a volume of RAM of $1$ GB = $1024$ MB $^{(1)}$. Each process takes 100 MB of RAM on the server. At the same time, the needs of maintaining the viability of the server takes about $100$ more megabytes of RAM. Thus, each server may have up to $9$ different processes of social network. Now each of the $n$ servers is running exactly $4$ processes. However, at the moment of peak load it is sometimes necessary to replicate the existing $4n$ processes by creating $8n$ new processes instead of the old ones. More formally, there is a set of replication rules, the $i$-th ($1 ≤ i ≤ 4n$) of which has the form of $a_{i} → (b_{i}, c_{i})$, where $a_{i}$, $b_{i}$ and $c_{i}$ ($1 ≤ a_{i}, b_{i}, c_{i} ≤ n$) are the numbers of servers. This means that instead of an old process running on server $a_{i}$, there should appear two new copies of the process running on servers $b_{i}$ and $c_{i}$. The two new replicated processes can be on the same server (i.e., $b_{i}$ may be equal to $c_{i}$) or even on the same server where the original process was (i.e. $a_{i}$ may be equal to $b_{i}$ or $c_{i}$). During the implementation of the rule $a_{i} → (b_{i}, c_{i})$ first the process from the server $a_{i}$ is destroyed, then appears a process on the server $b_{i}$, then appears a process on the server $c_{i}$. There is a set of $4n$ rules, destroying all the original $4n$ processes from $n$ servers, and creating after their application $8n$ replicated processes, besides, on each of the $n$ servers will be exactly $8$ processes. However, the rules can only be applied consecutively, and therefore the amount of RAM of the servers imposes limitations on the procedure for the application of the rules. According to this set of rules determine the order in which you want to apply all the $4n$ rules so that at any given time the memory of each of the servers contained at most $9$ processes (old and new together), or tell that it is impossible.
This problem may be solved by simulating the replication process. Let's keep a list of all replications that may be applied by the current step. Apply an arbitrary replication, after that update a list by adding/removing all suitable or now unsuitable replications touching all affected on current step servers. The list of replications may be kept in a "double-linked list" data structure, that allows to add and remove elements to/from the set and to extract an arbitrary element of the set in $O(1)$. The proof of correctness of such algorithm is not hard and is left as an exercies (maybe it will appear here later). We got a solution in $O(n)$ operation (though, the constant hidden by $O$-notation is pretty large; the input size is already $12n$ numbers and the solution itself hides a constant $36$ or higher).
[ "constructive algorithms", "greedy" ]
2,600
null
566
C
Logistical Questions
Some country consists of $n$ cities, connected by a railroad network. The transport communication of the country is so advanced that the network consists of a minimum required number of $(n - 1)$ bidirectional roads (in the other words, the graph of roads is a tree). The $i$-th road that directly connects cities $a_{i}$ and $b_{i}$, has the length of $l_{i}$ kilometers. The transport network is served by a state transporting company FRR (Fabulous Rail Roads). In order to simplify the price policy, it offers a single ride fare on the train. In order to follow the route of length $t$ kilometers, you need to pay $\displaystyle{\hat{\overline{{2}}}}$ burles. Note that it is forbidden to split a long route into short segments and pay them separately (a special railroad police, or RRP, controls that the law doesn't get violated). A Large Software Company decided to organize a programming tournament. Having conducted several online rounds, the company employees determined a list of finalists and sent it to the logistical department to find a place where to conduct finals. The Large Software Company can easily organize the tournament finals in any of the $n$ cities of the country, so the the main factor in choosing the city for the last stage of the tournament is the total cost of buying tickets for all the finalists. We know that the $i$-th city of the country has $w_{i}$ cup finalists living there. Help the company employees find the city such that the total cost of travel of all the participants to it is minimum.
Let's think about formal statement of the problem. We are given a tricky definition of a distance on the tre: $ \rho (a, b) = dist(a, b)^{1.5}$. Each vertex has its weight $w_{i}$. We need to choose a place $x$ for a competition such that the sum of distances from all vertices of the tree with their weights is minimum possible: $f(x) = w_{1} \rho (1, x) + w_{2} \rho (x, 2) + ... + w_{n} \rho (x, n)$. Let's understand how function $f(x)$ works. Allow yourself to put point $x$ not only in vertices of the tree, but also in any point inside each edge by naturally expanding the distance definition (for example, the middle of the edge of length $4$ km is located $2$ km from both ends of this edge). Fact 1. For any path $x\in[a,b]$ in the tree the function $ \rho (i, x)$ is convex. Actually, the function $dist(i, x)$ plot on each path $[a, b]$ looks like the plot of a function $abs(x)$: it first decreases linearly to the minimum: the closes to $i$ point on a segment $[a, b]$, and then increases linearly. Taking a composition with a convex increasing function $t^{1.5}$, as we can see, we get the convex function on any path in the tree. Here by function on the path we understand usual function of a real variable $x$ that is identified with its location on path $x$: $dist(a, x)$. So, each of the summands in the definition of $f(x)$ is convex on any path in the tree, so $f(x)$ is also convex on any path in the tree. Let's call convex functions on any path in the tree convex on tree. Let's formulate few facts about convex functions on trees. Fact 2. A convex function on tree can't have two different local minimums. Indeed, otherwise the path between those minimums contradicts the property of being convex on any path in the tree. So, any convex function $f(x)$ on the tree has the only local minimum that coincides with its global minimum. Fact 3. From each vertex $v$ there exists no more than one edge in which direction the function $f$ decreases. Indeed, otherwise the path connecting two edges of function decrease would contradict the definition of a convex function in a point $v$. Let's call such edge that function decreases along this edge to be a gradient of function $f$ in point $x$. By using facts 2 and 3 we see that in each vertex there is either a uniquely defined gradient or the vertex is a global minimum. Suppose we are able to efficiently find a gradient direction by using some algorithm for a given vertex $v$. If our tree was a bamboo then the task would be a usual convex function minimization that is efficiently solved by a binary search, i. e. dichotomy. We need some equivalent of a dichotomy for a tree. What is it? Let's use centroid decmoposition! Indeed, let's take a tree center (i. e. such vertex that sizes of all its subtrees are no larger than $n / 2$). By using fact $3$ we may consider the gradient of $f$ in the center of the tree. First of all, there may be no gradient in this point meaning that we already found an optimum. Otherwise we know that global minimum is located in a subtree in direction of gradient, so all remaining subtrees and the center can be excluded from our consideration. So, by running one gradient calculation we reduced the number of vertices in a considered part of a tree twice. So, in $O(\log n)$ runs of gradient calculation we almost solved the problem. Let's understand where exactly the answer is located. Note that the global optimum will most probably be located inside some edge. It is easy to see that the optimum vertex will be one of the vertices incident to that edge, or more specifically, one of the last two considered vertices by our algorithms. Which exactly can be determined by calculating the exact answer for them and choosing the most optimal among them. Now let's calculate the gradient direction in a vertex $v$. Fix a subtree $u_{i}$ of a vertex $v$. Consider a derivative of all summands from that subtree when we move into that subtree. Denote this derivative as $der_{i}$. Then, as we can see, the derivative of $f(x)$ while moving from $x = v$ in direction of subtree $u_{i}$ is $- der_{1} - der_{2} - ... - der_{i - 1} + der_{i} - der_{i + 1} - ... - der_{k}$ where $k$ is a degree of vertex $v$. So, by running one DFS from vertex $v$ we may calculate all values $der_{i}$, and so we may find a gradient direction by applying the formula above and considering a direction with negative derivative. Finally, we got a solution in $O(n\log n)$.
[ "dfs and similar", "divide and conquer", "trees" ]
3,000
null
566
D
Restructuring Company
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company. There are $n$ people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of $n$ departments, one person in each). However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use $team(person)$ to represent a team where person $person$ works. A crisis manager can make decisions of two types: - Merge departments $team(x)$ and $team(y)$ into one large department containing all the employees of $team(x)$ and $team(y)$, where $x$ and $y$ ($1 ≤ x, y ≤ n$) — are numbers of two of some company employees. If $team(x)$ matches $team(y)$, then nothing happens. - Merge departments $team(x), team(x + 1), ..., team(y)$, where $x$ and $y$ ($1 ≤ x ≤ y ≤ n$) — the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees $x$ and $y$ ($1 ≤ x, y ≤ n$) work at the same department. Help the crisis manager and answer all of his queries.
This problem allows a lot of solution with different time asymptotic. Let's describe a solution in $O(q\log n)$. Let's first consider a problem with only a queries of second and third type. It can be solved in a following manner. Consider a line consisting of all employees from $1$ to $n$. An observation: any department looks like a contiguous segment of workers. Let's keep those segments in any logarithmic data structure like a balanced binary search tree (std::set or TreeSet). When merging departments from $x$ to $y$, just extract all segments that are in the range $[x, y]$ and merge them. For answering a query of the third type just check if employees $x$ and $y$ belong to the same segment. In such manner we get a solution of an easier problem in $O(\log n)$ per query. When adding the queries of a first type we in fact allow some segments to correspond to the same department. Let's add a DSU for handling equivalence classes of segments. Now the query of the first type is just using merge inside DSU for departments which $x$ and $y$ belong to. Also for queries of the second type it's important not to forget to call merge from all extracted segments. So we get a solution in $O(q(\log n+\alpha(n)))=O(q\log n)$ time.
[ "data structures", "dsu" ]
1,900
null
566
E
Restoring Map
Archaeologists found some information about an ancient land of Treeland. We know for sure that the Treeland consisted of $n$ cities connected by the $n - 1$ road, such that you can get from each city to any other one along the roads. However, the information about the specific design of roads in Treeland has been lost. The only thing that the archaeologists can use is the preserved information about near cities. Two cities of Treeland were called near, if it were possible to move from one city to the other one by moving through at most two roads. Also, a city is considered near to itself. During the recent excavations archaeologists found a set of $n$ notes, each of them represents a list of cities, near to some of the $n$ cities of the country. However, unfortunately, none of the found records lets you understand in what order the cities go in the list and for which city in the list the near to it cities were listed. Help the archaeologists and restore any variant of the map of Treeland that meets the found information.
Let's call a neighborhood of a vertex - the set consisting of it and all vertices near to it. So, we know the set of all neighborhoods of all vertices in some arbitrary order, and also each neighborhood is shuffled in an arbitrary order. Let's call the tree vertex to be internal if it is not a tree leaf. Similarly, let's call a tree edge to be internal if it connects two internal vertices. An nice observation is that if two neighborhoods intersect exactly by two elements $a$ and $b$ then $a$ and $b$ have to be connected with an edge, in particular the edge $(a, b)$ is internal. Conversely, any internal edge $(a, b)$ may be represented as an intersection of some two neighborhoods $C$ and $D$ of some two vertices $c$ and $d$ such that there is a path $c - a - b - d$ in the tree. In such manner we may find all internal edges by considering pairwise intersections of all neighborhoods. This can be done in about $n^{3} / 2$ operations naively, or in $32$ times faster, by using bitsets technique. Note that knowing all internal edges we may determine all internal vertices except the only case of a star graph (i. e. the graph consisting of a vertex with several other vertices attached to it). The case of a star should be considered separately. Now we know the set of all leaves, all internal vertices and a tree structure on all internal vertices. The only thing that remained is to determine for each leaf, to what internal vertex is should be attached. This can be done in following manner. Consider a leaf $l$. Consider all neighborhoods containing it. Consider a minimal neighborhood among them; it can be shown that it is exactly the neighborhood $L$ corresponding to a leaf $l$ itself. Consider all internal vertices in $L$. There can be no less than two of them. If there are three of them or more then we can uniquely determine to which of them $l$ should be attached - it should be such vertex from them that has a degree inside $L$ larger than $1$. If there are exactly two internal vertices in $L$ (let's say, $a$ and $b$), then determining the attach point for $l$ is a bit harder. Statement: $l$ should be attached to that vertex among $a$, $b$, that has an internal degree exactly $1$. Indeed, if $l$ was attached to a vertex with internal degree larger than $1$, we would have considered this case before. If both of vertices $a$ and $b$ have internal degree - $1$ then our graph looks like a dumbbell (an edge $(a, b)$ and all remaining vertices attached either to $a$ or to $b$). Such case should also be considered separately. The solution for two special cases remains for a reader as an easy exercise.
[ "bitmasks", "constructive algorithms", "trees" ]
3,200
null
566
F
Clique in the Divisibility Graph
As you must know, the maximum clique problem in an arbitrary graph is $NP$-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively. Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques. Let's define a divisibility graph for a set of positive integers $A = {a_{1}, a_{2}, ..., a_{n}}$ as follows. The vertices of the given graph are numbers from set $A$, and two numbers $a_{i}$ and $a_{j}$ ($i ≠ j$) are connected by an edge if and only if either $a_{i}$ is divisible by $a_{j}$, or $a_{j}$ is divisible by $a_{i}$. You are given a set of non-negative integers $A$. Determine the size of a maximum clique in a divisibility graph for set $A$.
Order numbers in the sought clique in ascending order. Note that set $X = {x_{1}, ..., x_{k}}$ is a clique iff $\mathbb{Z}_{i}\ \mid\mathbb{Z}_{i+1}$ for ($1 \le i \le k - 1$). So, it's easy to formulate a dynamic programming problem: $D[x]$ is equal to the length of a longest suitable increasing subsequence ending in a number $x$. The calculation formula: $D[x]=m a x(1,m a x(D[y]+1\mathrm{~if~}y\mid x))$ for all $x$ in set $A$. If DP is written in "forward" direction then it's easy to estimate the complexity of a solution. In the worst case we'll process $n/1+n/2+\ldots+n/n=n(1/1+\ldots\cdot+1/n)\approx n\ln(n)$ transitions.
[ "dp", "math", "number theory" ]
1,500
null
566
G
Max and Min
Two kittens, Max and Min, play with a pair of non-negative integers $x$ and $y$. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, $x$ and $y$ became negative at the same time, and kitten Max tries to prevent him from doing so. Each kitten has a set of pairs of integers available to it. Kitten Max has $n$ pairs of non-negative integers $(a_{i}, b_{i})$ ($1 ≤ i ≤ n$), and kitten Min has $m$ pairs of non-negative integers $(c_{j}, d_{j})$ ($1 ≤ j ≤ m$). As kitten Max makes a move, it can take any available pair $(a_{i}, b_{i})$ and add $a_{i}$ to $x$ and $b_{i}$ to $y$, and kitten Min can take any available pair $(c_{j}, d_{j})$ and subtract $c_{j}$ from $x$ and $d_{j}$ from $y$. Each kitten can use each pair multiple times during distinct moves. Max moves first. Kitten Min is winning if at some moment both numbers $a$, $b$ are negative \textbf{simultaneously}. Otherwise, the winner of the game is kitten Max. Determine which kitten wins if both of them play optimally.
Consider a following geometrical interpretation. Both Max and Min have a set of vectors from the first plane quadrant and a point $(x, y)$. During his turn Max may add any of his vectors to a point $(x, y)$, and Min - may subtract any of his vectors. Min wants point $(x, y)$ to be strictly in the third quadrant, Max tries to prevent his from doing it. Denote Max vectors as $Mx_{i}$ and Min vectors as $Mn_{j}$. Consider a following obvious sufficient condition for Max to win. Consider some non-negative direction in a plane, i. e. such vector $(a, b)$ that $a, b \ge 0$ and at least one of numbers $a, b$ is not a zero. Then if among Max vectors there is such vector $Mx_{i}$, that it's not shorter than any of Min vectors $Mn_{j}$ along the direction $(a, b)$ then Max can surely win. Here by the length of vector $v$ along a direction $(a, b)$ we mean a scalar product of vector $v$ and vector $(a, b)$. Indeed, let Max always use that vector $Mx_{i}$. Then during the turns of Max and Min point $(x, y)$ is shifted by a vector $Mx_{i} - Mn_{j}$ for some $j$, so its overall shift along the vector $(a, b)$ is equal to $((Mx_{i} - Mn_{j}), (a, b)) = (Mx_{i}, (a, b)) - (Mn_{j}, (a, b)) \ge 0$. By observing that initially the scalar produt $((x, y), (a, b)) = ax + by > 0$ we see that at any moment $ax + by$ will be strictly positive. This means that Min won't be able at any moment to make $x$ and $y$ both be negative (since it would mean that $ax + by < 0$). Now let's formulate some kind of converse statement. Suppose Max vector $Mx_{i}$ lies strictly inside the triangle formed by Min vectors $Mn_{j}$ and $Mn_{k}$. In particular, vector $Mx_{i}$ endpoint can't lie on a segment $[Mn_{j}, Mn_{k}]$, but it may be collinear one of vectors $Mn_{j}$ and $Mn_{k}$. Note that since $Mx_{i}$ lies strictly inside the triangle formed by vectors $Mn_{j}$ and $Mn_{k}$ it can be extended to a vector $Mx'_{i}$, whose endpoint lies on a segment $[Mn_{j}, Mn_{k}]$. By using linear dependence of $Mx'_{i}$ and $Mn_{j}$, $Mn_{k}$ we have that $Mx'_{i} = (p / r)Mn_{j} + (q / r)Mn_{k}$, where $p + q = r$ and $p, q, r$ - integer non-negative numbers. This is equivalent to a formula $rMx'_{i} = pMn_{j} + qMn_{k}$. This means that if per each $r$ turns of Max in $Mx_{i}$ we will respond with $p$ turns of Min in $Mn_{j}$ and $q$ turns of Min in $Mn_{k}$, then the total shift will be equal to $- pMn_{j} - qMn_{k} + rMx_{i} = - rMx'_{i} + rMx_{i} = - r(Mx'_{i} - Mx_{i})$, that is the vector with strictly negative components. So, we are able to block that Max turn, i. e. it does not give any advantage to Max. The natural wish is to create a convex hull of all Min turns and to consider all Max turns in respect to it. If Max turn lies inside the convex hull of Min turns, then by using the previous fact this turn is meaningless to Max. Otherwise, there are two possibilities. First, this turn may intersect the hull but go out of it somewhere; in this case this Max turn is no shorter than all Min turns in some non-negative direction (more specifically, in its own direction), so Max wins. On the other hand, Max vector lies to aside from the Min turns convex hull. Let's suppose the vector $Mx_{i}$ lies to the left of the Min turns. This case requires a special analysis. Consider the topmost of the Min vectors $Mn_{j}$. If $Mx_{i}$ is no lower than $Mx_{j}$, then by using the first fact Max is able to win by using only this vector. Otherwise the difference $Mn_{i} - Mx_{j}$ is a vector with strictly negative components, by using which we are able to block that Max vector. So, the full version of a criteria for Min being a winner looks like the following. Consider a convex hull of Min turns and expand it to the left of the topmost point and to the bottom of the rightmost point. If all Max turns lie strictly inside the formed figure then Min wins, otherwise Max wins.
[ "geometry" ]
2,500
null
567
A
Lineland Mail
All cities of Lineland are located on the $Ox$ coordinate axis. Thus, each city is associated with its position $x_{i}$ — a coordinate on the $Ox$ axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in). Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city. For each city calculate two values ​​$min_{i}$ and $max_{i}$, where $min_{i}$ is the minimum cost of sending a letter from the $i$-th city to some other city, and $max_{i}$ is the the maximum cost of sending a letter from the $i$-th city to some other city
One can notice that the maximum cost of sending a letter from $i$'th city is equal to maximum of distances from $i$'th city to first city and from $i$'th city to last ($max(abs(x_{i} - x_{0}), abs(x_{i} - x_{n - 1})$). On the other hand, the minimum cost of sending a letter will be the minimum of distances between neighboring cities ($i - 1$'th and $i + 1$'th cities), more formally, $min(abs(x_{i} - x_{i - 1}), abs(x_{i} - x_{i + 1})$. For each city, except the first and the last this formula is correct, but for them formulas are ($abs(x_{i} - x_{i + 1})$) and ($abs(x_{i} - x_{i - 1})$) respectively.
[ "greedy", "implementation" ]
900
null
567
B
Berland National Library
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room. Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from $1$ to $10^{6}$. Thus, the system logs events of two forms: - "+ $r_{i}$" — the reader with registration number $r_{i}$ entered the room; - "- $r_{i}$" — the reader with registration number $r_{i}$ left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors. Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence. Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
To answer the queries correct, we need to know if the person is still in the library. For that purpose we will use $in$ array of type $bool$. Also we will store two variables for the answer and ''current state'' (it will store the current number of people in the library). Let's call them $ans$ and $state$ respectively. Thus, if we are given query $+ a_{i}$ then we should increase $state$ by one, mark that this person entered the library ($in[a_{i}] = true$) and try to update the answer ($ans = max(ans, state)$). Otherwise we are given $- a_{i}$ query. If the person who leaves the library, was in there, we should just decrease $state$ by one. Otherwise, if this person was not in the library ($in[a_{i}]$ == $false$) and leaves now, he entered the library before we started counting. It means we should increase the answer by one anyway. Also one should not forget that it is needed to mark that the person has left the library ($in[a_{i}] = false$).
[ "implementation" ]
1,300
null
567
C
Geometric Progression
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer $k$ and a sequence $a$, consisting of $n$ integers. He wants to know how many subsequences of length three can be selected from $a$, so that they form a geometric progression with common ratio $k$. A subsequence of length three is a combination of three such indexes $i_{1}, i_{2}, i_{3}$, that $1 ≤ i_{1} < i_{2} < i_{3} ≤ n$. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio $k$ is a sequence of numbers of the form $b·k^{0}, b·k^{1}, ..., b·k^{r - 1}$. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
Let's solve this problem for fixed middle element of progression. This means that if we fix element $a_{i}$ then the progression must consist of $a_{i} / k$ and $a_{i} \cdot k$ elements. It could not be possible, for example, if $a_{i}$ is not divisible by $k$ ($a_{i}\ \mathrm{mod}\ k\not=0$). For fixed middle element one could find the number of sequences by counting how many $a_{i} / k$ elements are placed left from fixed element and how many $a_{i} \cdot k$ are placed right from it, and then multiplying this numbers. To do this, one could use two associative arrays $A_{l}$ and $A_{r}$, where for each key $x$ will be stored count of occurences of $x$ placed left (or right respectively) from current element. This could be done with map structure. Sum of values calculated as described above will give the answer to the problem.
[ "binary search", "data structures", "dp" ]
1,700
null
567
D
One-Dimensional Battle Ships
Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of $n$ square cells (that is, on a $1 × n$ table). At the beginning of the game Alice puts $k$ ships on the field without telling their positions to Bob. Each ship looks as a $1 × a$ rectangle (that is, it occupies a sequence of $a$ consecutive squares of the field). The ships cannot intersect and even touch each other. After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit"). But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss". Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.
First, we should understand when the game ends. It will happen when on the $n$-sized board it will be impossible to place $k$ ships of size $a$. For segment with length $len$ we could count the maximum number of ships with size $a$ that could be placed on it. Each ship occupies $a + 1$ cells, except the last ship. Thus, for segment with length $len$ the formula will look like $\frac{t e n+1}{a+1}$ (we add "fictive" cell to $len$ cells to consider the last ship cell). This way, for $[l..r]$ segment the formula should be $\frac{r-l+2}{a+1}$. For solving the problem we should store all the $[l..r]$ segments which has no ''free'' cells (none of them was shooted). One could use ($std: : set$) for that purpose. This way, before the shooting, there will be only one segment $[1..n]$. Also we will store current maximum number of ships we could place on a board. Before the shooting it is equal to $\frac{n\i+1}{a+1}$. With every shoot in cell $x$ we should find the segment containing shooted cell (let it be $[l..r]$), we should update segment set. First, we should delete $[l..r]$ segment. It means we should decrease current maximum number of ships by $\frac{r-l+2}{a+1}$ and delete it from the set. Next, we need to add segments $[l..x - 1]$ and $[x + 1..r]$ to the set (they may not be correct, so you may need to add only one segments or do not add segments at all) and update the maximum number of ships properly. We should process shoots one by one, and when the maximum number of ships will become lesser than $k$, we must output the answer. If that never happen, output $- 1$.
[ "binary search", "data structures", "greedy", "sortings" ]
1,700
null
567
E
President and Roads
Berland has $n$ cities, the capital is located in city $s$, and the historic home town of the President is in city $t$ ($s ≠ t$). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town $t$, for which his motorcade passes along some path from $s$ to $t$ (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from $s$ to $t$, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.
At first, let's find edges that do not belong to any shortest paths from $s$ to $t$. Let's find two shortest path arrays $d1$ and $d2$ with any shortest-path-finding algorithm. First array stores shortest path length from $s$, and the second - from $t$. Edge $(u, v)$ then will be on at least one shortest path from $s$ to $t$ if and only if $d1[u] + w(u, v) + d2[v]$ == $d1[t]$. Let's build shortest path graph, leaving only edges described above. If we consider shortest path from $s$ to $t$ as segment $[0..D]$ and any edge $(u, v)$ in shortest path graph as its subsegment $[d1[u]..d1[v]]$, then if such subsegment do not share any common point with any other edge subsegment, except its leftest and rightest point ($d1[u]$ and $d1[v]$), this edge belongs to every shortest path from $s$ to $t$. Now we could surely answer "YES" to such edges. Next part of the solution are much simple. If edge $(u, v)$ do not belong to every shortest path, we could try decrease its weight. This edge will belong to every shortest path if and only if its weight will become $d1[t] - d1[u] - d2[v] - 1$. So, if this value are strictly positive, we should answer "CAN" considering new edge weight. Otherwise we need to output "NO".
[ "dfs and similar", "graphs", "hashing", "shortest paths" ]
2,200
null
567
F
Mausoleum
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital. The mausoleum will be constructed from $2n$ blocks, each of them has the shape of a cuboid. Each block has the bottom base of a $1 × 1$ meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of $n$ meters. The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement: - $[1, 2, 2, 3, 4, 4, 3, 1]$; - $[1, 1]$; - $[2, 2, 1, 1]$; - $[1, 2, 3, 3, 2, 1]$. Suddenly, $k$ more requirements appeared. Each of the requirements has the form: "$h[x_{i}]$ sign$_{i}$ $h[y_{i}]$", where $h[t]$ is the height of the $t$-th block, and a sign$_{i}$ is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the $k$ additional requirements is given by a pair of indexes $x_{i}$, $y_{i}$ ($1 ≤ x_{i}, y_{i} ≤ 2n$) and sign sign$_{i}$. Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the $k$ additional requirements were met.
Consider that we are placing blocks by pairs, one pair by one, starting from leftmost and rightmost places. Thus, for example, two blocks of height 1 we could place in positions 1 and 2, 1 and $2n$, or $2n - 1$ and $2n$. The segment of unused positions will be changed that way and the next block pairs should be placed on new leftmost and rightmost free places. At last only two positions will be free and we should place two blocks of height $n$ on them. Any correct sequence of blocks could be builded that way. Let's try to review the requirements consider such way of placing blocks. As soon as we place blocks one by one, the requirements are now only describes the order of placing blocks. For example, requirement ''3 >= 5'' means that we should place block in position 3 only if block in position 5 is already placed (and thus it have lesser height), or we place pair of blocks of same height on them at one moment. For counting required number of sequences we will use dynamic programming approach. Let's count $dp[l][r]$ - the number of ways to place some blocks in the way that only positions at segment $[l..r]$ are free. The height of current placed pair of blocks is counted from the segment borders itself ($\textstyle{\frac{(I+(n-r))}{2}}$. Fix one way of placing current block pair (exclusion is $l = = r + 1$). Now check if such placing meets the requirements. We will consider only requirements that meets one of the current-placing positions. For every "current" position "<" must be true only for free positions (positions in $[l..r]$, which do not equal to current positions), ">" must be true for already-placed positions (out of $[l..r]$) and "=" must be true only for second current position. This DP could be easily calculated using "lazy" approach.
[ "dp" ]
2,400
null
568
A
Primes or Palindromes?
Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this! Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one. Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left. One problem with prime numbers is that there are too many of them. Let's introduce the following notation: $π(n)$ — the number of primes no larger than $n$, $rub(n)$ — the number of palindromic numbers no larger than $n$. Rikhail wants to prove that there are a lot more primes than palindromic ones. He asked you to solve the following problem: for a given value of the coefficient $A$ find the maximum $n$, such that $π(n) ≤ A·rub(n)$.
It is known that amount of prime numbers non greater than $n$ is about $\frac{J h}{\log n}$. We can also found the amount of palindrome numbers with fixed length $k$ - it is about $10^{\lfloor{\frac{k+1}{2}}\rfloor}$ which is $O({\sqrt{n}})$. Therefore the number of primes asymptotically bigger than the number of palindromic numbers and for every constant $A$ there is an answer. Moreover, for this answer $n$ the next condition hold: $\Lambda\sim\frac{\sqrt{n}}{\log n}$. In our case $n < 10^{7}$. For all numbers smaller than $10^{7}$ we can check if they are primes (via sieve of Eratosthenes) and/or palindromes (via trivial algorithm or compute reverse number via dynamic approach). Then we can calculate prefix sums ($ \pi (n)$ and $rub(n)$) and find the answer using linear search. For $A \le 42$ answer is smaller than $2 \cdot 10^{6}$. Complexity - $O(a n s\cdot\log\log a n s)$.
[ "brute force", "implementation", "math", "number theory" ]
1,600
null
568
B
Symmetric and Transitive
Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation. A set $ρ$ of pairs $(a, b)$ of elements of some set $A$ is called a binary relation on set $A$. For two elements $a$ and $b$ of the set $A$ we say that they are in relation $ρ$, if pair $(a,b)\in\rho$, in this case we use a notation $a\stackrel{p}{\sim}b$. Binary relation is equivalence relation, if: - It is reflexive (for any $a$ it is true that $a\stackrel{p}{\sim}a$); - It is symmetric (for any $a$, $b$ it is true that if $a\stackrel{p}{\sim}b$, then $b\stackrel{p}{\sim}a$); - It is transitive (if $a\stackrel{p}{\sim}b$ and $b\sim c$, than $a\stackrel{p}{\sim}c$). Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof": Take any two elements, $a$ and $b$. If $a\stackrel{p}{\sim}b$, then $b\stackrel{p}{\sim}a$ (according to property (2)), which means $a\stackrel{p}{\sim}a$ (according to property (3)). It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong. Here's your task: count the number of binary relations over a set of size $n$ such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive). Since their number may be very large (not $0$, according to Little Johnny), print the remainder of integer division of this number by $10^{9} + 7$.
Let's find Johnny's mistake. It is all right in his proof except ``If $a\stackrel{\rho}{\sim}b$'' part. What if there is no such $b$ for an given $a$? Then obviously $a\stackrel{p}{\sim}a$ otherwise we'll take $b = a$. We can see that our binary relation is some equivalence relation which was expanded by some "empty" elements. For "empty" element $a$ there is no such $b$ that $a\stackrel{p}{\sim}b$. Thus we can divide our solution into two parts: Count the number of equivalence relations on sets of size $0, 1, ..., n - 1$ For every size count the number of ways to expand it with some "empty" elements. We can define equivalence relation using its equivalence classes. So first part can be solved using dynamic programming: $dp[elems][classes]$ - the numbers of ways to divide first $elems$ elements to $classes$ equivalence classes. When we handle next element we can send it to one of the existing equivalence classes or we can create new class. Let's solve second part. Consider set of size $m$. We have found that there are $eq[m]$ ways to build equivalence relation on this set. We have to add $n - m$ "empty" elements to this set. The number of ways to choose their positions is $C_{n}^{k}$. We can calculate all the binomial coefficients using Pascal's triangle. So the answer to the problem is $\textstyle\sum_{m=0}^{n-1}C[n][n-m]\cdot e q[m]$. Complexity - $O(n^{2})$
[ "combinatorics", "dp", "math" ]
1,900
null
568
C
New Language
Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed. After some time, the wise men returned from the trip even wiser. They locked up for six months in the dining room, after which they said to the king: "there are a lot of different languages, but almost all of them have letters that are divided into vowels and consonants; in a word, vowels and consonants must be combined correctly." There are very many rules, all of them have exceptions, but our language will be deprived of such defects! We propose to introduce a set of formal rules of combining vowels and consonants, and include in the language all the words that satisfy them. The rules of composing words are: - The letters are divided into vowels and consonants in some certain way; - All words have a length of exactly $n$; - There are $m$ rules of the form ($pos_{1}, t_{1}, pos_{2}, t_{2}$). Each rule is: if the position $pos_{1}$ has a letter of type $t_{1}$, then the position $pos_{2}$ has a letter of type $t_{2}$. You are given some string $s$ of length $n$, it is not necessarily a correct word of the new language. Among all the words of the language that lexicographically not smaller than the string $s$, find the minimal one in lexicographic order.
Suppose we have fixed letters on some positions, how can we check is there a way to select letters on other positions to build a word from the language? The answer is 2-SAT. Let's see: for every position there is two mutually exclusive options (vowel or consonant) and the rules are consequences. Therefore we can do this check in $O(n + m)$ time. Let's decrease the length of the prefix which will be the same as in $s$. Then the next letter must be strictly greater but all the next letters can be any. We can iterate over all greater letters and then check if we can made this word the word from the language (via 2-SAT). Once we have found such possibilty we have found the right prefix of the answer. After that we can increase the length of the fixed prefix in a similar way. This solution works in $O(nm \Sigma )$ time. We can divide this by $ \Sigma $ simply try not all the letter but only the smallest possible vowel and the smallest possible consonant. And you should remember about the case when all the letters are vowel (or all the letters are consonant). Complexity - $O(nm)$
[ "2-sat", "greedy" ]
2,600
null
568
D
Sign Posts
One Khanate had a lot of roads and very little wood. Riding along the roads was inconvenient, because the roads did not have road signs indicating the direction to important cities. The Han decided that it's time to fix the issue, and ordered to put signs on every road. The Minister of Transport has to do that, but he has only $k$ signs. Help the minister to solve his problem, otherwise the poor guy can lose not only his position, but also his head. More formally, every road in the Khanate is a line on the $Oxy$ plane, given by an equation of the form $Ax + By + C = 0$ ($A$ and $B$ are not equal to 0 at the same time). You are required to determine whether you can put signs in at most $k$ points so that each road had at least one sign installed.
Suppose, that solution exist. In case $n \le k$ we can put one signpost on each road. In other case let's choose any $k + 1$ roads. By the Dirichlet's principle there are at least two roads among selected, which have common signpost. Let's simple iterate over all variants with different two roads. After choosing roads $a$ and $b$, we will remove all roads, intersecting with $a$ and $b$ in common points and reduce $k$ in our problem. This recursive process solves the problem (if solution exist). Complexity of this solution - $O(n\cdot{\frac{k(k+1)!}{2^{k}}})$. If implement this solution carefully - you will get AC =) But in case of TL we can add one improvement to our solution. Note, that if we find point, which belongs to $k + 1$ or more roads, then we must include this point to out answer. For sufficiently large $n$ (for example, if $n > 30k^{2}$) this point always exist and we can find it using randomize algorithm. If solution exist, probability that two arbitrary roads are intersects in such a point not less than $\textstyle{\frac{1}{k}}$. Because of it, if we $100$ times pick two random roads, then with probability $1-10^{-8}$ such a point will be found and we can decrease $k$. All operations better to do in integers. Complexity - $O(n k^{2}+k^{2}\cdot{\frac{k!(k+1)!}{2^{k}}})$.
[ "brute force", "geometry", "math" ]
2,800
null
568
E
Longest Increasing Subsequence
Note that the memory limit in this problem is less than usual. Let's consider an array consisting of positive integers, some positions of which contain gaps. We have a collection of numbers that can be used to fill the gaps. Each number from the given collection can be used at most once. Your task is to determine such way of filling gaps that the longest increasing subsequence in the formed array has a maximum size.
Let's calculate array $c$: $c[len]$ - minimal number that can complete increasing subsequence of length $len$. (This is one of the common solution for LIS problem). Elements of this array are increasing and we can add new element $v$ to processed part of sequence as follows: find such index $i$ that $c[i] \le v$ and $c[i + 1] \ge v$ let $c[i + 1] = v$ We can process this action in $O(\log n)$ time. When we handle a gap, we must try to insert all numbers from set $b$. If we sort elements of $b$ in advance, then we can move with two iterators along arrays $b$ and $c$ and relax all needed values as explained above. This case requires $O(n + m)$ time. Authors implied solution with $O(n)$ space complexity for answer restoring. We can do this in the following way: Together with array $c$ we will store array $c_{index}[len]$ - index of element, which complete optimal increasing subsequence of length $len$. If this subsequence ends in a gap - we will store $- 1$. Also, we will store for every not gap - length of LIS($lenLIS[pos]$), which ends in this position (this is simply calculating while processing array $c$) and position($prevIndex[pos]$) of previous element in this subsequence (if this elements is gap, we store $- 1$) Now we will start recovery the answer with this information. While we are working with not gaps - it's all right. We can simply restore LIS with $prevIndex[pos]$ array. The main difficulty lies in processing gaps. If value of $prevIndex[pos]$ in current position equal to $- 1$ - we know, that before this elements must be one or more gaps. And we can determine which gaps and what values from $b$ we must put in them as follows: Let suppose that we stand at position $r$ (and $prevIndex[r] = - 1$). Now we want to find such position $l$ (which is not gap), that we can fill exactly $lenLIS[r] - lenLIS[l]$ gaps between $l$ with increasing numbers from interval $(a[l]..a[r])$. Position $l$ we can simply iterates from $r - 1$ to $0$ and with it calculating gaps between $l$ and $r$. Check the condition described above we can produce via two binary search query to array $b$. Few details: How do we know, that between positions $l$ and $r$ we can fill gaps in such a way, that out answer still the best? Let $countSkip(l, r)$ - count gaps on interval $(l..r)$, $countBetween(x, y)$ - count different numbers from set $b$, lying in the range $(x..y)$. Then, positions $l$ and $r$ are good only if $lenLIS[r] - lenLIS[l] = min(countSkip(l, r), countBetween(a[l], a[r]))$. $countSkip$ we can calculate while iterates position $l$, $countBetween(x, y) = max(0, lower_bound(b, y) - upper_bound(b, x))$. What to do, is LIS ends or begins in gaps? This case we can solve by simply adding $- \infty $ and $+ \infty $ in begin and end of out array. Complexity - $O(n\log n+k(n+m))$. Memory - $O(n + m)$.
[ "data structures", "dp" ]
3,000
null
569
A
Music
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk. Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is $T$ seconds. Lesha downloads the first $S$ seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For $q$ seconds of real time the Internet allows you to download $q - 1$ seconds of the track. Tell Lesha, for how many times he will start the song, including the very first start.
Suppose we have downloaded $S$ seconds of the song and press the 'play' button. Let's find how many seconds will be downloaded when we will be forced to play the song once more. ${\frac{x}{q}}={\frac{x-S}{q-1}}$. Hence $x = qS$. Solution: let's multiply $S$ by $q$ while $S < T$. The answer is the amount of operations. Complexity - $O(\log T)$
[ "implementation", "math" ]
1,500
null
569
B
Inventory
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with $1$. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for $n$ items in the company. Renumber items so that their inventory numbers form a permutation of numbers from $1$ to $n$ by changing the number of as few items as possible. Let us remind you that a set of $n$ numbers forms a permutation if all the numbers are in the range from $1$ to $n$, and no two numbers are equal.
Let's look at the problem from another side: how many numbers can we leave unchanged to get permutation? It is obvious: these numbers must be from $1$ to $n$ and they are must be pairwise distinct. This condition is necessary and sufficient. This problem can be solved with greedy algorithm. If me meet the number we have never met before and this number is between $1$ and $n$, we will leave this number unchanged. To implement this we can use array where we will mark used numbers. After that we will look over the array again and allocate numbers that weren't used. Complexity - $O(n)$.
[ "greedy", "math" ]
1,200
null
570
A
Elections
The country of Byalechinsk is running elections involving $n$ candidates. The country consists of $m$ cities. We know how many people in each city voted for each candidate. The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index. At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index. Determine who will win the elections.
We need to determine choice for each city. Then sum it for each candidate and determine the winner. $O(n * m)$
[ "implementation" ]
1,100
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #include <string> #include <fstream> #include <assert.h> #include <list> #include <cstring> using namespace std; #define name "" typedef unsigned long long ull; typedef long long ll; #define mk make_pair #define forn(i, n) for(ll i = 0; i < (ll)n; i++) #define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++) #define times clock() * 1.0 / CLOCKS_PER_SEC #define inb push_back struct __isoff{ __isoff(){ if (_ijps) freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);//, freopen("test.txt", "w", stderr); //else freopen(name".in", "r", stdin), freopen(name".out", "w", stdout); //ios_base::sync_with_stdio(0); srand(time(0)); //srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A'); } ~__isoff(){ //if(_ijps) cout<<times<<'\n'; } } __osafwf; const ull p1 = 31; const ull p2 = 29; const double eps = 1e-8; const double pi = acos(-1.0); const ll inf = 1e17 + 7; const int infi = 1e9 + 7; const ll dd = 8e7 + 7; const ll mod = 1e9 + 7; int D[105]; int main(){ int n, m; cin >> n >> m; forn(i, m){ int z = -1, t = 0; forn(j, n){ int g; cin >> g; if(z < g) z = g, t = j; } D[t]++; } int res = 0; forn(i, n){ if(D[res] < D[i]) res = i; } cout << res + 1; }
570
B
Simple Game
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from $1$ to $n$. Let's assume that Misha chose number $m$, and Andrew chose number $a$. Then, by using a random generator they choose a random integer $c$ in the range between $1$ and $n$ (any integer from $1$ to $n$ is chosen with the same probability), after which the winner is the player, whose number was closer to $c$. The boys agreed that if $m$ and $a$ are located on the same distance from $c$, Misha wins. Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number $n$. You need to determine which value of $a$ Andrew must choose, so that the probability of his victory is the highest possible. More formally, you need to find such integer $a$ ($1 ≤ a ≤ n$), that the probability that $|c-a|<|c-m|$ is maximal, where $c$ is the equiprobably chosen integer from $1$ to $n$ (inclusive).
Lets find which variant is interesting. For Andrew is no need a variant wherein $|a - m| > 1$ because we can increase probability of victory if we will be closer to m. Then we consider two variants, $a = c - 1$ and $a = c + 1$. Probability of victory will be $c / n$ for first variant and $(n - c + 1) / n$ for second. We need to choose better variant, also we must keep in mind case of $n = 1$. $O(1)$
[ "constructive algorithms", "games", "greedy", "implementation", "math" ]
1,300
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #include <string> #include <fstream> #include <assert.h> #include <list> #include <cstring> using namespace std; #define name "" typedef unsigned long long ull; typedef long long ll; #define mk make_pair #define forn(i, n) for(ll i = 0; i < (ll)n; i++) #define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++) #define times clock() * 1.0 / CLOCKS_PER_SEC #define inb push_back struct __isoff{ __isoff(){ if (_ijps) freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);//, freopen("test.txt", "w", stderr); //else freopen(name".in", "r", stdin), freopen(name".out", "w", stdout); //ios_base::sync_with_stdio(0); srand(time(0)); //srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A'); } ~__isoff(){ //if(_ijps) cout<<times<<'\n'; } } __osafwf; const ull p1 = 31; const ull p2 = 29; const double eps = 1e-8; const double pi = acos(-1.0); const ll inf = 1e17 + 7; const int infi = 1e9 + 7; const ll dd = 8e7 + 7; const ll mod = 1e9 + 7; int main(){ ll n, m; cin >> n >> m; if(n == 1){ cout << 1; return 0; } if(m - 1 < n - m){ cout << m + 1; } else{ cout << m - 1; } }
570
C
Replacement
Daniel has a string $s$, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string $s$, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string $s$ contains no two consecutive periods, then nothing happens. Let's define $f(s)$ as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left. You need to process $m$ queries, the $i$-th results in that the character at position $x_{i}$ ($1 ≤ x_{i} ≤ n$) of string $s$ is assigned value $c_{i}$. After each operation you have to calculate and output the value of $f(s)$. Help Daniel to process all queries.
Lets find how replacements occur. If we have segment of points with length $l$,we need $l - 1$ operations and stop replacements for this segment. If we sum lenghts of all segments and its quantity then answer will be = total length of segments - quantity of segments. After change of one symbol length changes by 1. Quantity of segments can be supported by array. Consider events of merging, dividing,creation and deletion of segments. For merging we need to find if both of neighbors(right and left) are points then merging occured and quantity of segments reduced by 1. Other cases can be cosidered similarly. $O(n + m)$
[ "constructive algorithms", "data structures", "implementation" ]
1,600
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #include <string> #include <fstream> #include <assert.h> #include <list> #include <cstring> using namespace std; #define name "" typedef unsigned long long ull; typedef long long ll; #define mk make_pair #define forn(i, n) for(ll i = 0; i < (ll)n; i++) #define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++) #define times clock() * 1.0 / CLOCKS_PER_SEC #define inb push_back struct __isoff{ __isoff(){ if (_ijps) freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);//, freopen("test.txt", "w", stderr); //else freopen(name".in", "r", stdin), freopen(name".out", "w", stdout); //ios_base::sync_with_stdio(0); srand(time(0)); //srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A'); } ~__isoff(){ //if(_ijps) cout<<times<<'\n'; } } __osafwf; const ull p1 = 31; const ull p2 = 29; const double eps = 1e-8; const double pi = acos(-1.0); const ll inf = 1e17 + 7; const int infi = 1e9 + 7; const ll dd = 3e5 + 7; const ll mod = 1e9 + 7; string s; char t = '.'; int n, m; int num, group; bool ok[dd]; int main(){ cin >> n >> m >> s; forn(i, n){ if(s[i] == t){ num++; if(i == 0 || s[i - 1] != t) group++; ok[i + 1] = 1; } } forn(i, m){ int d; char c; scanf("%d %c", &d, &c); bool a = ok[d], b = c == t; if(a != b){ if(a){ num--; } else{ num++; } if(ok[d - 1] && ok[d + 1] && !b){ group++; } if(ok[d - 1] && ok[d + 1] && b){ group--; } if(!ok[d - 1] && !ok[d + 1] && !b){ group--; } if(!ok[d - 1] && !ok[d + 1] && b){ group++; } } ok[d] = b; printf("%d\n", num - group); } }
570
D
Tree Requests
Roman planted a tree consisting of $n$ vertices. Each vertex contains a lowercase English letter. Vertex $1$ is the root of the tree, each of the $n - 1$ remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex $i$ is vertex $p_{i}$, the parent index is always less than the index of the vertex (i.e., $p_{i} < i$). The depth of the vertex is the number of nodes on the path from the root to $v$ along the edges. In particular, the depth of the root is equal to $1$. We say that vertex $u$ is in the subtree of vertex $v$, if we can get from $u$ to $v$, moving from the vertex to the parent. In particular, vertex $v$ is in its subtree. Roma gives you $m$ queries, the $i$-th of which consists of two numbers $v_{i}$, $h_{i}$. Let's consider the vertices in the subtree $v_{i}$ located at depth $h_{i}$. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.
We need to write vertices in DFS order and store time of enter/exit of vertices in DFS. All vertices in subtree represent a segment. Now we can get all vertices in subtree v on height h as a segment, making two binary searches. We can make a palindrome if quantity of uneven entries of each letter is less than 2. This function can be counted for each prefix in bypass for each depth. For saving the memory bit compression can be used considering that we need only parity and function is xor. $O(m * (log + 26) + n)$ D had a offline solution too in $O(n + m * (26 / 32))$ time and $O(n * 26 / 8)$ memory
[ "binary search", "bitmasks", "constructive algorithms", "dfs and similar", "graphs", "trees" ]
2,200
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #include <string> #include <fstream> #include <assert.h> #include <list> #include <cstring> using namespace std; #define name "" typedef unsigned long long ull; typedef long long ll; #define mk make_pair #define forn(i, n) for(ll i = 0; i < (ll)n; i++) #define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++) #define times clock() * 1.0 / CLOCKS_PER_SEC #define inb push_back struct __isoff{ __isoff(){ if (_ijps) freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);//, freopen("test.txt", "w", stderr); //else freopen(name".in", "r", stdin), freopen(name".out", "w", stdout); //ios_base::sync_with_stdio(0); srand(time(0)); //srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A'); } ~__isoff(){ //if(_ijps) cout<<times<<'\n'; } } __osafwf; const ull p1 = 31; const ull p2 = 29; const double eps = 1e-8; const double pi = acos(-1.0); const ll inf = 1e17 + 7; const int infi = 1e9 + 7; const ll dd = 2e6 + 7; const ll mod = 1e9 + 7; int n, m; vector<int> P[dd]; vector<pair<int, int> > H[dd]; int In[dd], Out[dd]; int A[30]; int ti = 0; string s; void dfs(int v, int h){ In[v] = ++ti; H[h].push_back(mk(ti, H[h].back().second ^ A[s[v] - 'a'])); forn(i, P[v].size()) dfs(P[v][i], h + 1); Out[v] = ++ti; } int main(){ cin >> n >> m; forn(i, n) H[i].resize(1); forn(i, 30) A[i] = 1 << i; forn(i, n - 1){ int t; scanf("%d", &t); P[t - 1].push_back(i + 1); } cin >> s; dfs(0, 0); forn(i, m){ int h, v; scanf("%d%d", &v, &h); v--, h--; int l = lower_bound(H[h].begin(), H[h].end(), mk(In[v], -1)) - H[h].begin() - 1; int r = lower_bound(H[h].begin(), H[h].end(), mk(Out[v], -1)) - H[h].begin() - 1; int t = H[h][l].second ^ H[h][r].second; bool ok = t - (t & -t); if(!ok) printf("Yes\n"); else printf("No\n"); } }
570
E
Pig and Palindromes
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of $n$ rows and $m$ columns. We enumerate the rows of the rectangle from top to bottom with numbers from $1$ to $n$, and the columns — from left to right with numbers from $1$ to $m$. Let's denote the cell at the intersection of the $r$-th row and the $c$-th column as $(r, c)$. Initially the pig stands in cell $(1, 1)$, and in the end she wants to be in cell $(n, m)$. Since the pig is in a hurry to get home, she can go from cell $(r, c)$, only to either cell $(r + 1, c)$ or $(r, c + 1)$. She cannot leave the forest. The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem). Count the number of beautiful paths from cell $(1, 1)$ to cell $(n, m)$. Since this number can be very large, determine the remainder after dividing it by $10^{9} + 7$.
We need palindrome paths. Palindrome is word which reads the same backward or forward. We can use it. Count the dynamic from coordinates of 2 cells, first and latest in palindrome. From each state exists 4 transitions (combinations: first cell down/to the right and second cell up/to the left). We need only transitions on equal symbols for making a palindrome. Note that we need a pairs of cells on equal distance from start and end for each. For saving memory we need to store two latest layers. $O(n^{3})$ - time and $O(n^{2})$ - memory
[ "combinatorics", "dp" ]
2,300
#define _ijps 0 #define _CRT_SECURE_NO_DEPRECATE #pragma comment(linker, "/STACK:667772160") #include <iostream> #include <cmath> #include <vector> #include <time.h> #include <map> #include <set> #include <deque> #include <cstdio> #include <cstdlib> #include <unordered_map> #include <bitset> #include <algorithm> #include <string> #include <fstream> #include <assert.h> #include <list> #include <cstring> using namespace std; #define name "" typedef unsigned long long ull; typedef long long ll; #define mk make_pair #define forn(i, n) for(ll i = 0; i < (ll)n; i++) #define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++) #define times clock() * 1.0 / CLOCKS_PER_SEC #define inb push_back struct __isoff{ __isoff(){ if (_ijps) freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);//, freopen("test.txt", "w", stderr); //else freopen(name".in", "r", stdin), freopen(name".out", "w", stdout); //ios_base::sync_with_stdio(0); srand(time(0)); //srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A'); } ~__isoff(){ //if(_ijps) cout<<times<<'\n'; } } __osafwf; const ull p1 = 31; const ull p2 = 29; const double eps = 1e-8; const double pi = acos(-1.0); const ll inf = 1e17 + 7; const int infi = 1e9 + 7; const ll dd = 500 + 7; const ll mod = 1e9 + 7; int n, m, t; vector< vector<int> > Dp, Pdp; pair<int, int> in[dd][2 * dd]; int ou[dd][dd]; char C[dd][dd]; int main(){ cin >> n >> m; forn(i, dd){ forn(j, dd){ int x = i - j, y = j; if(x >= n || x < 0 || y >= m || y < 0) continue; ou[x][y] = j; in[j][x + y] = mk(x, y); } } forn(i, dd){ forn(j, dd){ int x = n - 1 - j, y = i + j; if(x >= n || x < 0 || y >= m || y < 0) continue; ou[x][y] = j; in[j][x + y] = mk(x, y); } } vector<int> Si(n + m); forn(i, n){ forn(j, m){ Si[i + j]++; } } forn(i, n){ forn(j, m){ cin >> C[i][j]; } } int ts = (n + m - 2) / 2; int t = Si[ts]; Dp.resize(t, vector<int>(t)); forn(x, t){ forn(y, t){ int x1 = in[x][ts].first, y1 = in[x][ts].second; int x2 = in[y][n + m - 2 - ts].first, y2 = in[y][n + m - 2 - ts].second; if ((x1 == x2 && (y1 == y2 || y1 + 1 == y2)) || (y1 == y2 && (x1 == x2 || x1 + 1 == x2))) Dp[x][y] = C[x1][y1] == C[x2][y2]; } } for (ts--; ts >= 0; ts--){ t = Si[ts]; Pdp.assign(t, vector<int>(t)); forn(x, t){ forn(y, t){ int x1 = in[x][ts].first, y1 = in[x][ts].second; int x2 = in[y][n + m - 2 - ts].first, y2 = in[y][n + m - 2 - ts].second; if(C[x1][y1] == C[x2][y2]){ ll s = 0; if (x2 - 1 >= 0 && x1 + 1 < n) s += Dp[ou[x1 + 1][y1]][ou[x2 - 1][y2]]; if (y2 - 1 >= 0 && x1 + 1 < n) s += Dp[ou[x1 + 1][y1]][ou[x2][y2 - 1]]; if (x2 - 1 >= 0 && y1 + 1 < m) s += Dp[ou[x1][y1 + 1]][ou[x2 - 1][y2]]; if (y2 - 1 >= 0 && y1 + 1 < m) s += Dp[ou[x1][y1 + 1]][ou[x2][y2 - 1]]; Pdp[x][y] = s % mod; } } } swap(Pdp, Dp); } cout << Dp[0][0]; }
571
A
Lengthening Sticks
You are given three sticks with positive integer lengths of $a, b$, and $c$ centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most $l$ centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.
Let's count the number of ways to form a triple which can't represent triangle sides, and then we subtract this value from $C_{l+3}^{3}={\stackrel{(l+1)(l+2)(l+3)}{6}}$ - the total number of ways to increase the sticks not more than $l$ in total. This number is obtained from partition of $l$ into 4 summands ($l_{a} + l_{b} + l_{c} + unused_{l} = l$), or can be counted using a for loop. Now we consider triples $a + l_{a}, b + l_{b}, c + l_{c}$, where $l_{a} + l_{b} + l_{c} \le l, l_{a}, l_{b}, l_{c} \ge 0$. Fix the maximal side, for example it would be $a + l_{a}$. We'll have to do the following algo for $b + l_{b}$ and $c + l_{c}$ in the same way. The triple is not a triangle with maximal side $a + l_{a}$ if $a + l_{a} \ge b + l_{b} + c + l_{c}$. If we iterate over $l_{a}$ between $0$ and $l$, we have the following conditions on $l_{b}, l_{c}$: $l_{b} + l_{c} \le a - b - c + l_{a},$ $l_{b} + l_{c} \le l - l_{a},$ $l_{b}, l_{c} \ge 0.$ So, non-negative integers $l_{b}, l_{c}$ should be such that $l_{b} + l_{c} \le min(a - b - c + l_{a}, l - l_{a})$. If we denote this minimum as $x$ than we can choose $l_{b}, l_{c}$ in $\textstyle{\frac{(x+1)(x+2)}{2}}$ different ways (again we divide $x$ into three summands: $l_{b}, l_{c}$ and some unused volume). Also when we fix $l_{b}$, there are $x - l_{b} + 1$ ways to choose $l_{c}$, so the overall number of pair $l_{b}, l_{c}$ is $\sum_{l_{b}=0}^{x}(x-l_{b}+1)=\sum_{a=1}^{x+1}a={\frac{(x+1)(x+2)}{2}},$ so we obtain the same formula. To sum up, we need to iterate over the maximal side and over the addition to that side, then write these formulas, and subtract the result from the total number of different additions to the sides. The complexity of the solution is $O(l)$.
[ "combinatorics", "implementation", "math" ]
2,100
#pragma comment (linker, "/STACK:1280000000") #define _CRT_SECURE_NO_WARNINGS //#include "testlib.h" #include <cstdio> #include <cassert> #include <algorithm> #include <iostream> #include <memory.h> #include <string> #include <vector> #include <set> #include <map> #include <cmath> #include <bitset> #include <deque> //#include <unordered_map> //#include <unordered_set> #include <ctime> #include <stack> #include <queue> #include <fstream> using namespace std; //#define FILENAME "" #define mp make_pair #define all(a) a.begin(), a.end() typedef long long li; typedef long double ld; void solve(); void precalc(); clock_t start; //int timer = 1; bool todo = true; int main() { #ifdef room111 freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #else //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); //freopen(FILENAME".in", "r", stdin); //freopen(FILENAME ".out", "w", stdout); #endif int t = 1; cout.sync_with_stdio(0); cin.tie(0); precalc(); cout.precision(10); cout << fixed; //cin >> t; start = clock(); int testNum = 1; while (t--) { //cout << "Case #" << testNum++ << ": "; solve(); //++timer; } #ifdef room111 cerr << "\n\n" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << "\n\n"; #endif return 0; } //BE CAREFUL: IS INT REALLY INT? //#define int li /*int pr[] = { 97, 2011 }; int mods[] = { 1000000007, 1000000009 }; const int C = 100500; int powers[2][C];*/ int MOD = 1000000007; //int c[5010][5010]; //int catalan[200500]; //ld doubleC[100][100]; int binpow(int q, int w, int mod) { if (!w) return 1; if (w & 1) return q * 1LL * binpow(q, w - 1, mod) % mod; return binpow(q * 1LL * q % mod, w / 2, mod); } void precalc() { /*for (int w = 0; w < 2; ++w) { powers[w][0] = 1; for (int j = 1; j < C; ++j) { powers[w][j] = (powers[w][j - 1] * 1LL * pr[w]) % mods[w]; } }*/ /*catalan[0] = 1; for (int n = 0; n < 200500 - 1; ++n) { catalan[n + 1] = catalan[n] * 2 * (2 * n + 1) % MOD * binpow(n + 2, MOD - 2, MOD) % MOD; }*/ /*for (int i = 0; i < 5010; ++i) { c[i][i] = c[i][0] = 1; for (int j = 1; j < i; ++j) { c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD; } }*/ /*for (int i = 0; i < 100; ++i) { doubleC[i][i] = doubleC[i][0] = 1.0; for (int j = 1; j < i; ++j) { doubleC[i][j] = doubleC[i - 1][j - 1] + doubleC[i - 1][j]; } }*/ } int gcd(int q, int w) { while (w) { q %= w; swap(q, w); } return q; } #define int li //int mod = 1000000007; int cnt(int a, int b, int c, int s) { if (s + a < b + c) { return 0; } int cur = min(s, (s + a - b - c) / 2); return (cur + 1) * (cur + 2) / 2; } void solve() { int a[3]; int L; for (int i = 0; i < 3; ++i) { cin >> a[i]; } cin >> L; int ans = 0; for (int i = 0; i <= L; ++i) { ans += (L - i + 1) * (L - i + 2) / 2; } for (int i = 0; i < 3; ++i) { for (int s = 0; s <= L; ++s) { ans -= cnt(a[i], a[(i + 1) % 3], a[(i + 2) % 3], s); } } cout << ans << "\n"; }
571
B
Minimization
You've got array $A$, consisting of $n$ integers and a positive integer $k$. Array $A$ is indexed by integers from $1$ to $n$. You need to permute the array elements so that value \[ \sum_{i=1}^{n-k}|A[i]-A[i+k]| \] became minimal possible. In particular, it is allowed not to change order of elements at all.
We can divide all indices $[1;n]$ into groups by their remainder modulo $k$. While counting $\sum_{i=1}^{n-k}|a_{i}-a_{i+k}|$, we can consider each group separately and sum the distances between neighbouring numbers in each group. Consider one group, corresponding to some remainder $i$ modulo $k$, i.e. containing $a_{j}$ for $j\equiv i\mod(k)$. Let's write down its numbers from left to right: $b_{1}, b_{2}, ..., b_{m}$. Then this group adds to the overall sum the value $\sum_{j=1}^{m-1}|b_{j}-b_{j+1}|.$ We can notice that if we sort $b_{1}, ..., b_{m}$ in non-decreasing order, this sum will not increase. So, in the optimal answer we can consider that numbers in each group don't decrease. Furthermore, in that case this sum is equal to $|b_{m} - b_{1}|$. Now consider two groups $b_{1}, ..., b_{m}$ and $c_{1}, c_{2}, ..., c_{l}$, both sorted in non-decreasing order. We claim that either $b_{1} \ge c_{l}$ or $b_{m} \le c_{1}$, i.e. segments $[b_{1}, b_{m}]$ and $[c_{1}, c_{l}]$ can have common points only in their endpoints. Why is this true? These groups add $|b_{m} - b_{1}| + |c_{l} - c_{1}|$ to the overall sum. We consider the case $c_{1} \ge b_{1}$, the other is symmetric. If $c_{1} < b_{m}$, then swapping $c_{1}$ and $b_{m}$ will not increase the values these groups add to the answer, since the right border of $b$ group moves to the left, and the left border of $c$ group moves to the right. So, $c_{1} \ge b_{m}$ in that case, and the assertion is proved. Now we know that the values in each group should from a continuous segment of the sorted original array. In fact, we have $k-(n\mod k)$ groups of size $\scriptstyle{\frac{n}{k}}$ (so called small groups) and $(n\mod k)$ groups of size $\textstyle{\binom{n}{k}}$ (so called large groups). Consider the following dynamic programming: $dp[L][S]$ - the minimal sum of values added to the answer by $L$ large groups and $S$ small groups, if we choose the elements for them from the first $L\cdot({\frac{n}{k}}+1)+S\cdot{\frac{n}{k}}$ elements of the sorted array $A$. There are no more than $O(k^{2})$ states, and each transition can be made in $O(1)$: we choose large or small group to add and obtain the number it adds to the sum by subtracting two elements of the sorted array. The answer for the problem will be in $d p[(n\mathrm{\boldmath~\mod~}k)][k-(n\mathrm{\boldmath~\mod~}k)]$. The overall complexity of the solution is $O(n\log n+k^{2})$. We can note that in pretests $(n\mod k)$ was quite small, and some slower solutions could pass, but they failed on final tests.
[ "dp", "greedy", "sortings" ]
2,000
#define _CRT_SECURE_NO_WARNINGS #pragma comment (linker, "/STACK:128000000") #include <stdio.h> #include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> #include <queue> #include <deque> #include <cmath> #include <ctime> #include <stack> #include <set> #include <map> #include <cassert> #include <memory.h> #include <sstream> using namespace std; #define mp make_pair #define pb push_back #define all(a) a.begin(), a.end() #define forn(i, n) for (int i = 0; i < (int)(n); ++i) typedef long long li; typedef long long i64; typedef double ld; typedef vector<int> vi; typedef pair <int, int> pi; void solve(); void precalc(); int TESTNUM = 0; #define FILENAME "" int main() { string s = FILENAME; #ifdef AIM //assert(!s.empty()); freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); //cerr<<FILENAME<<endl; //assert (s != "change me please"); clock_t start = clock(); #else //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); //freopen(FILENAME ".in", "r", stdin); //freopen(FILENAME ".out", "w", stdout); cin.tie(0); #endif cout.sync_with_stdio(0); cout.precision(10); cout << fixed; precalc(); int t = 1; //cin >> t; while (t--) { ++TESTNUM; solve(); } #ifdef AIM cerr << "\n\n\n" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << "\n\n\n"; #endif return 0; } //#define int li /*int pr[] = { 97, 2011 }; int mods[] = { 1000000007, 1000000009 }; const int C = 100500; int powers[2][C];*/ int MOD = 1000000007; //int c[5010][5010]; //int catalan[200500]; //ld doubleC[100][100]; int binpow(int q, int w, int mod) { if (!w) return 1; if (w & 1) return q * 1LL * binpow(q, w - 1, mod) % mod; return binpow(q * 1LL * q % mod, w / 2, mod); } void precalc() { /*for (int w = 0; w < 2; ++w) { powers[w][0] = 1; for (int j = 1; j < C; ++j) { powers[w][j] = (powers[w][j - 1] * 1LL * pr[w]) % mods[w]; } }*/ /*catalan[0] = 1; for (int n = 0; n < 200500 - 1; ++n) { catalan[n + 1] = catalan[n] * 2 * (2 * n + 1) % MOD * binpow(n + 2, MOD - 2, MOD) % MOD; }*/ /*for (int i = 0; i < 5010; ++i) { c[i][i] = c[i][0] = 1; for (int j = 1; j < i; ++j) { c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD; } }*/ /*for (int i = 0; i < 100; ++i) { doubleC[i][i] = doubleC[i][0] = 1.0; for (int j = 1; j < i; ++j) { doubleC[i][j] = doubleC[i - 1][j - 1] + doubleC[i - 1][j]; } }*/ } int gcd(int q, int w) { while (w) { q %= w; swap(q, w); } return q; } //#define int li //int mod = 1000000007; void solve() { int n, k; cin >> n >> k; int part = n / k; int large = n % k; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(all(a)); vector<vector<int>> dp(large + 1, vector<int>(k - large + 1, 2e9)); dp[0][0] = 0; for (int largeParts = 0; largeParts <= large; ++largeParts) { for (int smallParts = 0; smallParts <= k - large; ++smallParts) { int nex = largeParts * (part + 1) + smallParts * part; if (largeParts < large) { int add = a[nex + part] - a[nex]; dp[largeParts + 1][smallParts] = min(dp[largeParts + 1][smallParts], dp[largeParts][smallParts] + add); } if (smallParts < k - large) { int add = a[nex + part - 1] - a[nex]; dp[largeParts][smallParts + 1] = min(dp[largeParts][smallParts + 1], dp[largeParts][smallParts] + add); } } } cout << dp[large][k - large] << "\n"; }
571
C
CNF 2
'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form) In the other words, CNF is a formula of type $\left(v_{11}\mid v_{12}\mid\cdot\cdot\cdot\mid v_{1k_{1}}\rangle\,\Re(v_{21}\mid v_{22}\mid\cdot\cdot\cdot\mid v_{2k_{2}})\,\hat{G}\cdot\cdot\cdot\cdot\hat{G}(v_{l1}\mid v_{l2}\mid\cdot\cdot\cdot\cdot\mid v_{l k_{l}})\right),$, where $&$ represents a logical "AND" (conjunction), represents a logical "OR" (disjunction), and $v_{ij}$ are some boolean variables or their negations. Each statement in brackets is called a clause, and $v_{ij}$ are called literals. You are given a CNF containing variables $x_{1}, ..., x_{m}$ and their negations. We know that each variable occurs in at most two clauses (with negation and without negation in total). Your task is to determine whether this CNF is satisfiable, that is, whether there are such values of variables where the CNF value is true. If CNF is satisfiable, then you also need to determine the values of the variables at which the CNF is true. It is guaranteed that each variable occurs at most once in each clause.
Firstly let's assign values to variables occurring in our fomula only with negation or only without negation. After that we can throw away the disjuncts which contained them, since they are already true, and continue the process until it is possible. To make it run in time limit, one should use dfs or bfs algorithm to eliminate these variables and disjuncts. So now we have only variables which have both types of occurrences in disjucnts. Let's build a graph with the vertices corresponding to disjuncts, and for each varible $a$ make an edge between the disjuncts that contain $a$ and $!a$. Now we should choose the directions of edges in this graph in such a way that every vertex has at least one incoming edge. We can notice that if some connected component of this graph is a tree, the solution is not possible: on each step we can take some leaf of this tree, and we have to orient its only edge to it, and then erase the leaf. In the end we'll have only one vertex, and it'll not have any incoming edges. Otherwise, take some cycle in the component and orient the edges between neighbouring vertices along it. Then run dfs from every vertex of the cycle and orient each visited edge in the direction we went along it. It is easy to easy that after this process every vertex will have at least one incoming edge. So, we should consider cases with the variables which values can be assigned at once, than construct a graph from disjuncts and variables and find whether each connected component has a cycle. If so, we also should carefully construct the answer, assigning the remaining variables their values, looking at the directions of the edges in the graph. The overall complexity is $O(n + m)$.
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
2,500
#pragma comment (linker, "/STACK:128000000") //#include "testlib.h" #include <cstdio> #include <cassert> #include <algorithm> #include <iostream> #include <memory.h> #include <string> #include <vector> #include <set> #include <map> #include <cmath> #include <bitset> //#include <unordered_map> //#include <unordered_set> #include <ctime> #include <stack> #include <queue> using namespace std; //#define FILENAME "" #define mp make_pair #define all(a) a.begin(), a.end() typedef long long li; typedef long double ld; void solve(); void precalc(); clock_t start; //int timer = 1; bool doing = true; int main() { #ifdef AIM freopen("input.txt", "r", stdin); //freopen("out.txt", "w", stdout); #else //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); //freopen(FILENAME".in", "r", stdin); //freopen(FILENAME ".out", "w", stdout); #endif int t = 1; cout.sync_with_stdio(0); cin.tie(0); precalc(); cout.precision(10); cout << fixed; //cin >> t; start = clock(); int testNum = 1; while (t--) { //cout << "Case #" << testNum++ << ": "; solve(); //++timer; } #ifdef room111 cerr << "\n\n" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << "\n\n"; #endif return 0; } //BE CAREFUL: IS INT REALLY INT? //#define int li void precalc() { } int binpow(int q, int w, int mod) { if (!w) return 1; if (w & 1) return q * binpow(q, w - 1, mod) % mod; return binpow(q * q % mod, w / 2, mod); } int gcd(int q, int w) { while (w) { q %= w; swap(q, w); } return q; } vector<vector<pair<int, int>>> dis; vector<vector<vector<int>>> has; vector<char> done; vector<int> res; void erase(vector<int>& cur, int val) { for (auto it = cur.begin(); it != cur.end(); ++it) { if (*it == val) { cur.erase(it); return; } } assert(false); } void dfs(int v) { if (res[v] != -1) { return; } assert(has[v][0].size() == 0 || has[v][1].size() == 0); bool have = false; for (int j = 0; j < 2; ++j) { if (!have && has[v][j].size() == 0) { res[v] = j ^ 1; have = true; continue; } vector<int> now = has[v][j]; for (int num : now) { if (done[num]) { continue; } done[num] = true; for (auto liter : dis[num]) { int var = liter.first; int type = liter.second; erase(has[var][type], num); if (has[var][type].empty()) { dfs(var); } } } } } vector<vector<int>> gr; vector<int> mt; vector<int> revmt; vector<char> used; bool try_kuhn(int v) { if (used[v]) { return false; } used[v] = true; for (size_t i = 0; i<gr[v].size(); ++i) { int to = gr[v][i]; if (mt[to] == -1 || try_kuhn(mt[to])) { mt[to] = v; revmt[v] = to; return true; } } return false; } void solve() { int n, vars; scanf("%d%d", &n, &vars); dis.resize(n); has.assign(vars, vector<vector<int>>(2)); for (int i = 0; i < n; ++i) { int k; scanf("%d", &k); dis[i].resize(k); for (int j = 0; j < k; ++j) { int cur; scanf("%d", &cur); int type = 1; if (cur < 0) { type = 0; cur = -cur; } --cur; dis[i][j] = make_pair(cur, type); has[cur][type].push_back(i); } } done.assign(n, false); res.assign(vars, -1); for (int i = 0; i < vars; ++i) { for (int j = 0; j < 2; ++j) { if (has[i][j].empty()) { dfs(i); } } } gr.resize(n); for (int i = 0; i < n; ++i) { if (done[i]) { continue; } for (auto item : dis[i]) { gr[i].push_back(item.first); } } mt.assign(vars, -1); revmt.assign(n, -1); for (int run = 1; run;) { run = 0; used.assign(n, false); for (int v = 0; v < n; ++v) { if (!done[v] && revmt[v] == -1 && try_kuhn(v)) { run = 1; } } } for (int i = 0; i < n; ++i) { if (done[i]) { continue; } int cur = revmt[i]; if (cur == -1) { cout << "NO\n"; return; } int type = -1; for (auto item : dis[i]) { if (item.first == cur) { type = item.second; break; } } assert(type != -1); res[cur] = type; } cout << "YES\n"; for (int i = 0; i < vars; ++i) { if (res[i] == -1) { res[i] = 0; } cout << res[i]; } cout << "\n"; }
571
D
Campus
Oscolcovo city has a campus consisting of $n$ student dormitories, $n$ universities and $n$ military offices. Initially, the $i$-th dormitory belongs to the $i$-th university and is assigned to the $i$-th military office. Life goes on and the campus is continuously going through some changes. The changes can be of four types: - University $a_{j}$ merges with university $b_{j}$. After that all the dormitories that belonged to university $b_{j}$ are assigned to to university $a_{j}$, and university $b_{j}$ disappears. - Military office $c_{j}$ merges with military office $d_{j}$. After that all the dormitories that were assigned to military office $d_{j}$, are assigned to military office $c_{j}$, and military office $d_{j}$ disappears. - Students of university $x_{j}$ move in dormitories. Lets $k_{xj}$ is the number of dormitories that belong to this university at the time when the students move in. Then the number of students in each dormitory of university $x_{j}$ increases by $k_{xj}$ (note that the more dormitories belong to the university, the more students move in each dormitory of the university). - Military office number $y_{j}$ conducts raids on all the dormitories assigned to it and takes all students from there. Thus, at each moment of time each dormitory is assigned to exactly one university and one military office. Initially, all the dormitory are empty. Your task is to process the changes that take place in the campus and answer the queries, how many people currently live in dormitory $q_{j}$.
Let's suppose for each dormitory from $Q$ query we already know the last raid moment. When task will be much easier: we can throw away $M$ and $Z$ queries and to get right answer we should subtract two values: people count in dormitory right now and same count in a last raid moment. On this basis, we have such plan: For each $Q$ query let's find the last raid moment using $M$ and $Z$ queries. Find people count in two interesting moments using $U$ and $A$ queries. Calculcates the final answer. Let's try to solve the first part. We want to make such queries on disjoint sets: Merge two sets ($M$ query). Assign value $time$ for all elements in particular set ($Z$ query). Get value for a particular element ($Q$ query). To solve this task we'll use a well-known technique: "merge smaller set to bigger". We'll maintain such values: $elements$ - set elements. $set_id$ - for each element their set id. $last_set_update_time$ - last moment when assign operation has occurred for each set. $last_update_time$ - last moment when assign operation has occurred for each element. $actual_time$ - moment of time when $last_update_time$ was actually for the element. Let's focus on $actual_time$ value. It's obvious that when we merge two sets each element can have a different last assign moment. But after first assignment all elements from any set will have the same value. So the answer for $Q$ query for element $i$ from set $s$: If last_set_update_time[s]=actual_time[i] then last_update_time[i] else last_set_update_time[s] For each $Z$ query you should just update $last_set_update_time$ array. It's easy to maintain this values when you merge two sets: Let's suppose we want to merge set $from$ to set $to$. For each element from set $from$ we already know last assign time. So just update $last_update_time$ with this value and $actual_time$ is equal of last assign operation for set $to$. The second part of the solution is the same as first one. $O(n * lg(n) + m)$ time and $O(n + m)$ memory.
[ "binary search", "data structures", "dsu", "trees" ]
3,100
#pragma comment (linker, "/STACK:128000000") //#include "testlib.h" #include <cstdio> #include <cassert> #include <algorithm> #include <iostream> #include <memory.h> #include <string> #include <vector> #include <set> #include <map> #include <cmath> #include <bitset> //#include <unordered_map> //#include <unordered_set> #include <ctime> #include <stack> #include <queue> using namespace std; //#define FILENAME "" #define mp make_pair #define all(a) a.begin(), a.end() typedef long long li; typedef long double ld; void solve(); void precalc(); clock_t start; //int timer = 1; bool doing = true; int main() { #ifdef room81 freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #else //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); //freopen(FILENAME".in", "r", stdin); //freopen(FILENAME ".out", "w", stdout); #endif int t = 1; cout.sync_with_stdio(0); cin.tie(0); precalc(); cout.precision(10); cout << fixed; //cin >> t; start = clock(); int testNum = 1; while (t--) { //cout << "Case #" << testNum++ << ": "; solve(); //++timer; } #ifdef room81 cerr << "\n\n" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << "\n\n"; #endif return 0; } //BE CAREFUL: IS INT REALLY INT? //#define int li void precalc() { } int binpow(int q, int w, int mod) { if (!w) return 1; if (w & 1) return q * 1LL * binpow(q, w - 1, mod) % mod; return binpow(q * 1LL * q % mod, w / 2, mod); } int gcd(int q, int w) { while (w) { q %= w; swap(q, w); } return q; } //#define int li struct _node; typedef _node *node; struct _node { int cnt, prior; _node* l; _node* r; _node* p; li val; li add; int lastNull; int lastNullToPush; _node() :val(0), add(0), lastNull(0), lastNullToPush(0) { prior = (rand() << 16) | rand(); cnt = 1; l = nullptr; r = nullptr; p = nullptr; } inline void push() { if (l) { l->add += add; l->lastNullToPush = max(l->lastNullToPush, lastNullToPush); } if (r) { r->add += add; r->lastNullToPush = max(r->lastNullToPush, lastNullToPush); } lastNull = max(lastNull, lastNullToPush); val += add; add = 0; lastNullToPush = 0; } inline void recalc() { p = nullptr; cnt = 1 + Cnt(l) + Cnt(r); if (l) { l->p = this; } if (r) { r->p = this; } } static int Cnt(_node* v) { if (!v) return 0; return v->cnt; } node merge(node l, node r) { if (!l) return r; if (!r) return l; if (l->prior < r->prior) { l->push(); l->r = merge(l->r, r); l->recalc(); return l; } else { r->push(); r->l = merge(l, r->l); r->recalc(); return r; } } inline void split(node v, int key, node& l, node& r) { l = r = nullptr; if (!v) return; v->push(); int cur = Cnt(v->l); if (cur < key) { l = v; split(l->r, key - cur - 1, l->r, r); l->recalc(); } else { r = v; split(r->l, key, l, r->l); r->recalc(); } } node push_back(node other) { return merge(this, other); } int getLastZero(node v) { int res = v->lastNull; while (v) { res = max(res, v->lastNullToPush); v = v->p; } return res; } li getActualVal(_node* v) { li res = v->val; while (v) { res += v->add; v = v->p; } return res; } }; enum { UNI_MERGE = 0, WAR_MERGE = 1, UNI_ADD = 2, WAR_ZERO = 3, QUERY = 4 }; struct Query { int type; int q, w; int num; void scan() { char c; cin >> c; switch (c) { case 'U': type = UNI_MERGE; cin >> q >> w; --q; --w; break; case 'M': type = WAR_MERGE; cin >> q >> w; --q; --w; break; case 'A': type = UNI_ADD; cin >> q; --q; break; case 'Z': type = WAR_ZERO; cin >> q; --q; break; case 'Q': type = QUERY; cin >> q; --q; break; default: assert(false); } } }; vector<int> dsu[2]; int findSet(int id, int v) { if (dsu[id][v] == v) { return v; } return dsu[id][v] = findSet(id, dsu[id][v]); } void merge(int id, int q, int w) { dsu[id][w] = q; } void solve() { int n, Q; cin >> n >> Q; vector<Query> ask; vector<vector<pair<int, int>>> askNum(Q); for (int i = 0; i < Q; ++i) { Query cur; cur.scan(); cur.num = i; if (cur.type == QUERY) { askNum[i].push_back(mp(cur.q, i)); } ask.push_back(cur); } vector<li> res(Q, 0); for (int dom = 1; dom >= -1; dom -= 2) { vector<int> sizes(n, 1); vector<node> uni(n), war(n); vector<node> uniRoots(n), warRoots(n); for (int i = 0; i < n; ++i) { uni[i] = new _node(); war[i] = new _node(); uniRoots[i] = uni[i]; warRoots[i] = war[i]; } for (int w = 0; w < 2; ++w) { dsu[w].resize(n); for (int i = 0; i < n; ++i) { dsu[w][i] = i; } } for (int i = 0; i < Q; ++i) { for (auto item : askNum[i]) { int id = item.first; li curRes = uni[id]->getActualVal(uni[id]); res[item.second] += dom * curRes; } askNum[i].clear(); auto& curAsk = ask[i]; if (curAsk.type == QUERY) { int id = curAsk.q; int lastZero = war[id]->getLastZero(war[id]); askNum[lastZero].push_back(mp(id, i)); } if (curAsk.type == UNI_MERGE) { uniRoots[curAsk.q] = uniRoots[curAsk.q]->push_back(uniRoots[curAsk.w]); sizes[curAsk.q] += sizes[curAsk.w]; merge(0, curAsk.q, curAsk.w); } if (curAsk.type == WAR_MERGE) { warRoots[curAsk.q] = warRoots[curAsk.q]->push_back(warRoots[curAsk.w]); merge(1, curAsk.q, curAsk.w); } if (curAsk.type == UNI_ADD) { uniRoots[curAsk.q]->add += sizes[curAsk.q]; } if (curAsk.type == WAR_ZERO) { warRoots[curAsk.q]->lastNullToPush = i; } } } for (int i = 0; i < Q; ++i) { if (ask[i].type == QUERY) { cout << res[i] << "\n"; } } }
571
E
Geometric Progressions
Geometric progression with the first element $a$ and common ratio $b$ is a sequence of numbers $a, ab, ab^{2}, ab^{3}, ...$. You are given $n$ integer geometric progressions. Your task is to find the smallest integer $x$, that is the element of all the given progressions, or else state that such integer does not exist.
If intersection of two geometric progressions is not empty, set of common elements indexes forms arithmetic progression in each progression or consists of not more than one element. Let's intersect first progression with each other progression. If any of these intersections are empty then total intersection is empty. If some of these intersection consist of one element, then we could check only this element. Otherwise one could intersect arithmetic progressions of first progression indexes and take minimal element of this intersection. The remaining question is how intersect two geometric progression? Let's factorise all numbers in these two progressions and find set of appropriate indexes for every prime factor in both progressions. These progressions one need intersect both by values and by indexes.
[ "math" ]
3,200
#include <cstdio> #include <cstdlib> #include <cassert> #include <iostream> #include <set> #include <vector> #include <cstring> #include <string> #include <algorithm> #include <numeric> #include <cmath> #include <complex> #include <map> #include <queue> #include <time.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef vector<double> vd; typedef vector<vd> vvd; typedef pair<int, int> pii; typedef pair<double, double> pdd; typedef vector<pii> vii; typedef vector<string> vs; const int mod = 1000000007; time_t BEGIN; void out(const vi & v) { for (int i = 0; i < v.size(); ++i) cerr << v[i] << ' '; cerr << endl; } ll mpow(ll x, ll n) { ll res = 1; while (n) { if (n & 1) res = res * x % mod; n /= 2; x = x * x % mod; } return res; } ll inv (ll a, ll b) { a %= b; ll b0 = b; ll xa = 1, xb = 0, ya = 0, yb = 1; while (a % b != 0) { ll t = a / b; a = (a - t * b) % b0; xa = (xa - t * ya) % b0; xb = (xb - t * yb) % b0; swap(a, b); swap(xa, ya); swap(xb, yb); } ya %= b0; if (ya < 0) ya += b0; return ya; } ll lcm(ll x, ll y) { ll d = __gcd(x, y); x /= d; if (y) assert(x <= 1e18 / y); return x * y; } class AP { public: AP(ll s, ll T): s(s), T(T) {} AP& operator=(const AP & a) { T = a.T; s = a.s; return *this; } void out() { cerr << s << "+" << T << "k\n"; } ll T, s; }; AP strong_intersect(AP a, AP b) { if (a.T == b.T) { if (a.s == b.s) return a; return AP(-1, -1); } if (a.s == b.s) return AP(a.s, 0); if (a.s < b.s) swap(a, b); ll num = a.s - b.s; ll den = b.T - a.T; if (den < 0 || num % den != 0) return AP(-1, -1); ll index = num / den; return AP(a.s + a.T*index, 0); } ll mul(ll x, ll y, ll z) { if (x == 0 || y == 0) return 0; if (y < 0) { x = -x; y = -y; } ll res = 0; while (y) { if (y & 1) res = (res + x) % z; y /= 2; x = (x + x) % z; } return res; } AP intersect(AP a, AP b) { // a.out(); b.out(); if (a.s < 0 || b.s < 0) return AP(-1, -1); if (a.T == 0 && b.T == 0) { if (a.s == b.s) return a; return AP(-1, -1); } if (b.T == 0) swap(a, b); if (a.T == 0) { if (b.s > a.s || (a.s - b.s) % b.T != 0) return AP(-1, -1); return a; } ll d = __gcd(a.T, b.T); if (a.s % d != b.s % d) return AP(-1, -1); if (a.s < b.s) swap(a, b); ll x = (b.s - a.s) / d; // x <= 0 ll y = b.T / d; ll z = a.T / d; // (x + y*i) / z assert(y <= 1e18 / z); ll r = mul((-x) % z, inv(y, z), z); ll mi = r + z*max(0LL, (-x - r*y + z*y - 1) / (z*y)); assert(mi <= 1e18 / b.T); // cerr << x << ' ' << y << ' ' << z << ' ' << mi << endl; AP res(b.s + b.T * mi, lcm(a.T, b.T)); // cerr << "res "; res.out(); return res; } vi uniq_merge(const vi & a, const vi & b) { vi c(a.size() + b.size()); merge(a.begin(), a.end(), b.begin(), b.end(), c.begin()); c.resize(unique(c.begin(), c.end()) - c.begin()); return c; } int ord(int a, int p) { int cnt = 0; while (a % p == 0) { ++cnt; a /= p; } return cnt; } vi erat; vi get_primes(int n) { vi primes; for (int i = 2; i*i <= n; ++i) if (n % i == 0) { primes.push_back(i); while (n % i == 0) n /= i; } if (n > 1) primes.push_back(n); sort(primes.begin(), primes.end()); return primes; } ll fix(int A0, int B0, ll fix0, int A1, int B1, const vi & curp, bool & fail) { ll fix = -1; for (auto p : curp) { AP a0(ord(A0, p), ord(B0, p)); if (fix0 >= 0) { a0.s = a0.s + a0.T * fix0; a0.T = 0; } AP a1(ord(A1, p), ord(B1, p)); AP a2 = intersect(a0, a1); if (a2.s < 0) { fail = true; return -1; } if (a0.T == 0 && a1.T == 0 && a0.s != a1.s) { fail = true; return -1; } if (a2.T == 0 && a1.T != 0) { ll nfix = (a2.s - a1.s) / a1.T; if (fix != -1 && fix != nfix) { fail = true; return -1; } fix = nfix; } } return fix; } AP trace(AP a, AP b) { return AP((a.s - b.s) / b.T, a.T / b.T); } AP subsec(AP a, AP b) { return AP(a.s + a.T * b.s, a.T * b.T); } AP common(int A0, int B0, int A1, int B1, const vi & curp) { bool fail = false; ll fix1 = fix(A0, B0, -1, A1, B1, curp, fail); // cerr << "fix1 " << fix1 << ' ' << fail << endl; ll fix0 = fix(A1, B1, fix1, A0, B0, curp, fail); // cerr << "fix0 " << fix0 << ' ' << fail << endl; if (fail) { return AP(-1, -1); } if (fix0 >= 0) { ll fix1 = fix(A0, B0, fix0, A1, B1, curp, fail); if (fail || fix1 < 0) { return AP(-1, -1); } else { return AP(fix0, 0); } } AP intersection0(0, 1); AP intersection1(0, 1); bool was = false; for (auto p : curp) { AP a0(ord(A0, p), ord(B0, p)); AP a1(ord(A1, p), ord(B1, p)); AP a2 = intersect(a0, a1); if (a2.s < 0) return AP(-1, -1); if (a0.T == 0 && a1.T == 0) continue; AP new0 = trace(a2, a0);//((a2.s - a0.s) / a0.T, a2.T / a0.T); AP new1 = trace(a2, a1);//((a2.s - a1.s) / a1.T, a2.T / a1.T); if (!was) { intersection0 = new0; intersection1 = new1; was = 1; } else { // cerr << "new "; new0.out(); new1.out(); AP x0 = intersect(new0, intersection0); AP x1 = intersect(new1, intersection1); if (x0.s < 0 || x1.s < 0) return AP(-1, -1); AP subold0 = trace(x0, intersection0); AP subold1 = trace(x1, intersection1); AP subold2 = intersect(subold0, subold1); if (subold2.s < 0) return AP(-1, -1); intersection0 = subsec(intersection0, subold2); intersection1 = subsec(intersection1, subold2); // cerr << "traced inter "; intersection0.out(); intersection1.out(); AP subnew0 = trace(intersection0, new0); AP subnew1 = trace(intersection1, new1); AP subnew2 = strong_intersect(subnew0, subnew1); // cerr << "subnew "; subnew0.out(); subnew1.out(); subnew2.out(); if (subnew2.s < 0) return AP(-1, -1); intersection0 = subsec(new0, subnew2); intersection1 = subsec(new1, subnew2); } // cerr << "inter "; intersection0.out(); intersection1.out(); if (intersection1.T == 0) { ll fix1 = intersection1.s; ll fix0 = fix(A1, B1, fix1, A0, B0, curp, fail); if (fail || fix0 < 0) return AP(-1, -1); intersection0 = AP(fix0, 0); } if (intersection0.T == 0) { ll fix0 = intersection0.s; ll fix1 = fix(A0, B0, fix0, A1, B1, curp, fail); if (fail || fix1 < 0) { return AP(-1, -1); } else { return AP(fix0, 0); } } if (intersection0.s < 0 || intersection1.s < 0) return AP(-1, -1); } return intersection0; } bool check_geom(int a, int b, ll n) { if (n % a) return false; n /= a; if (b == 1) { return n == 1; } while (n > 1) { if (n % b) return false; n /= b; } return n == 1; } bool check_all_geoms(const vi & a, const vi & b, ll n) { for (int j = 0; j < a.size(); ++j) { if (!check_geom(a[j], b[j], n)) return false; } return true; } ll check_stupid(const vi & a, const vi & b, int start) { ll n = a[start]; while (1) { bool ok = true; for (int i = 0; i < a.size(); ++i) { if (!check_geom(a[i], b[i], n)) { ok = false; break; } } if (ok) { return n%mod; } if (n > 1e18 / b[start] || b[start] == 1) break; n *= b[start]; } return -1; } vi factor(int n, const vi & p) { vi pw(p.size()); for (int i = 0; i < p.size(); ++i) { while (n % p[i] == 0) { n /= p[i]; ++pw[i]; } } return pw; } int solve(const vi & a, const vi & b) { int n = a.size(); for (int i = 0; i < n; ++i) if (b[i] == 1) { for (int j = 0; j < n; ++j) { if (!check_geom(a[j], b[j], a[i])) return -1; } return a[i]; } vvi primes(n); for (int i = 0; i < n; ++i) { primes[i] = uniq_merge(get_primes(a[i]), get_primes(b[i])); } AP intersection(0, 1); for (int i = 1; i < n; ++i) { vi curp = uniq_merge(primes[0], primes[i]); intersection = intersect(intersection, common(a[0], b[0], a[i], b[i], curp)); if (intersection.s < 0) return -1; } return a[0]*mpow(b[0], intersection.s) % mod; } int stupid_solve(vi a, vi b) { vii ts(a.size()); for (int i = 0; i < a.size(); ++i) ts[i] = pii(a[i], b[i]); sort(ts.begin(), ts.end()); ts.resize(unique(ts.begin(), ts.end()) - ts.begin()); a.resize(ts.size()); b.resize(ts.size()); for (int i = 0; i < a.size(); ++i) { a[i] = ts[i].first; b[i] = ts[i].second; } /* int d = a[0]; for (int i = 0; i < a.size(); ++i) { d = __gcd(a, a[i]); } for (int i = 0; i < a.size(); ++i) { a[i] / d; }*/ for (int i = 0; i < a.size(); ++i) if (b[i] == 1) { for (int j = 0; j < a.size(); ++j) { if (!check_geom(a[j], b[j], a[i])) return -1; } return a[i]; } for (int i = 0; i < a.size(); ++i) { if (b[i] > b[0]) { swap(a[0], a[i]); swap(b[0], b[i]); break; } } vvi primes(a.size()); vvi primesa(a.size()); vvi primesb(a.size()); for (int i = 0; i < a.size(); ++i) { primes[i] = uniq_merge(get_primes(a[i]), get_primes(b[i])); primesa[i] = get_primes(a[i]); primesb[i] = get_primes(b[i]); } for (int i = 1; i < a.size(); ++i) { if (primes[i] != primes[i-1]) { int n = (primes[i].size() > primes[i-1].size()) ? a[i] : a[i-1]; if (!check_all_geoms(a, b, n)) return -1; else return n; } if (primesb[i] != primesb[i-1]) { int start = (primesb[i].size() > primesb[i-1].size()) ? i : i-1; return check_stupid(a, b, start); } } for (auto p : primesa[0]) if (!binary_search(primesb[0].begin(), primesb[0].end(), p)) { for (int i = 1; i < a.size(); ++i) { if (ord(a[i], p) != ord(a[i-1], p)) return -1; } } vvi pa(a.size()), pb(b.size()); for (int i = 0; i < a.size(); ++i) { pa[i] = factor(a[i], primesb[0]); pb[i] = factor(b[i], primesb[0]); } vi v = pa[0]; for (int pwb = 0; ; ++pwb) { double passed_time = (clock() - BEGIN) / (double)CLOCKS_PER_SEC; if (passed_time > 0.01) break; bool ok = true; for (int i = 1; i < a.size() && ok; ++i) { int div = 0; for (int j = 0; j < v.size(); ++j) { if (v[j] < pa[i][j] || (v[j] - pa[i][j]) % pb[i][j] != 0) { ok = false; break; } int ndiv = (v[j] - pa[i][j]) / pb[i][j]; if (j && ndiv != div) { ok = false; break; } div = ndiv; } } if (ok) { return a[0] * mpow(b[0], pwb) % mod; } for (int i = 0; i < v.size(); ++i) { v[i] += pb[0][i]; } } // return check_stupid(a, b, 0); return -1; } int main() { int n; while (cin >> n) { BEGIN = clock(); vi a(n), b(n); for (int i = 0; i < n; ++i) { scanf("%d%d", &a[i], &b[i]); } int res = solve(a, b); cout << res << endl; // int res1 = stupid_solve(a, b); // cout << res1 << endl; /* if (res != res1) { cerr << res1 << endl; out(a); out(b); assert(0); }*/ } return 0; }
572
A
Arrays
You are given two arrays $A$ and $B$ consisting of integers, \textbf{sorted in non-decreasing order}. Check whether it is possible to choose $k$ numbers in array $A$ and choose $m$ numbers in array $B$ so that any number chosen in the first array is strictly less than any number chosen in the second array.
In this problem one need to check whether it's possible to choose $k$ elements from array $A$ and $m$ elements from array $B$ so that each of chosen element in $A$ is less than each of chosen elements in $B$. If it's possible then it's possible to choose $k$ smallest elements in $A$ and $m$ largest elements in $B$. That means that in particular, $k$-th smallest element of $A$ is less than $m$-th largest element in $B$. So, if $A[k] < B[n - m + 1]$ then the answer is "YES" and if not, then the answer is "NO".
[ "sortings" ]
900
#include <cstdio> #include <cstdlib> #include <cassert> #include <iostream> #include <set> #include <vector> #include <cstring> #include <string> #include <algorithm> #include <numeric> #include <cmath> #include <complex> #include <map> #include <queue> using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef vector<double> vd; typedef vector<vd> vvd; typedef pair<int, int> pii; typedef pair<double, double> pdd; typedef vector<pii> vii; typedef vector<string> vs; int main() { int k, m, n1, n2; cin >> n1 >> n2 >> k >> m; vi a(n1); for (int i = 0; i < a.size(); ++i) cin >> a[i]; vi b(n2); for (int i = 0; i < b.size(); ++i) cin >> b[i]; if (a[k - 1] < b[n2 - m]) cout << "YES\n"; else cout << "NO\n"; return 0; }
572
B
Order Book
In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number $i$ has price $p_{i}$, direction $d_{i}$ — buy or sell, and integer $q_{i}$. This means that the participant is ready to buy or sell $q_{i}$ stocks at price $p_{i}$ for one stock. A value $q_{i}$ is also known as a volume of an order. All orders with the same price $p$ and direction $d$ are merged into one aggregated order with price $p$ and direction $d$. The volume of such order is a sum of volumes of the initial orders. An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order. An order book of depth $s$ contains $s$ best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than $s$ aggregated orders for some direction then all of them will be in the final order book. You are given $n$ stock exhange orders. Your task is to print order book of depth $s$ for these orders.
First of all the problem may be solved for buy orders and sell orders separately. The easiest soultion is to use structure like std::map or java.lang.TreeMap. To aggregate orders we just add volume to the corresponding map element: aggregated[price] += volume. After that we should extract lowest (or largest) element from map $s$ times (or while it's not empty). Complexity of this solution is $O(nlogn)$. It is also possible to solve the problem without data structres other than an array. You should just maintain at most $s$ best orders in sorted order and when adding another order you insert it in appropriate place and move worse elements in linear time of $s$. Complexity of this solution is $O(sn)$.
[ "data structures", "greedy", "implementation", "sortings" ]
1,300
/** * code generated by JHelper * More info: https://github.com/AlexeyDmitriev/JHelper * @author RiaD */ #include <iostream> #include <fstream> #include <iostream> #include <bits/stdc++.h> #include <iterator> #include <string> #include <stdexcept> #ifdef SPCPPL_DEBUG #define SPCPPL_ASSERT(condition) \ if(!(condition)) { \ throw std::runtime_error(std::string() + #condition + " in line " + std::to_string(__LINE__) + " in " + __PRETTY_FUNCTION__); \ } #else #define SPCPPL_ASSERT(condition) #endif /** * Support decrementing and multi-passing, but not declared bidirectional(or even forward) because * it's reference type is not a reference. * * It doesn't return reference because * 1. Anyway it'll not satisfy requirement [forward.iterators]/6 * If a and b are both dereferenceable, then a == b if and only if *a and * b are bound to the same object. * 2. It'll not work with reverse_iterator that returns operator * of temporary which is temporary for this iterator * * Note, reverse_iterator is not guaranteed to work now too since it works only with bidirectional iterators, * but it's seems to work at least on my implementation. * * It's not really useful anywhere except iterating anyway. */ template <typename T> class IntegerIterator : public std::iterator<std::input_iterator_tag, T, std::ptrdiff_t, T*, T> { public: explicit IntegerIterator(int value) : value(value) { } IntegerIterator& operator ++() { ++value; return *this; } IntegerIterator operator ++(int) { IntegerIterator copy = *this; ++value; return copy; } IntegerIterator& operator --() { --value; return *this; } IntegerIterator operator --(int) { IntegerIterator copy = *this; --value; return copy; } T operator *() const { return value; } bool operator ==(IntegerIterator rhs) { return value == rhs.value; } bool operator !=(IntegerIterator rhs) { return !(*this == rhs); } private: T value; }; template <typename T> class IntegerRange { public: IntegerRange(T begin, T end) : begin_(begin), end_(end) { } IntegerIterator<T> begin() const { return IntegerIterator<T>(begin_); } IntegerIterator<T> end() const { return IntegerIterator<T>(end_); } private: T begin_; T end_; }; template <typename T> class ReversedIntegerRange { typedef std::reverse_iterator<IntegerIterator<T>> IteratorType; public: ReversedIntegerRange(T begin, T end) : begin_(begin), end_(end) { } IteratorType begin() const { return IteratorType(IntegerIterator<T>(begin_)); } IteratorType end() const { return IteratorType(IntegerIterator<T>(end_)); } private: T begin_; T end_; }; template <typename T> IntegerRange<T> range(T to) { SPCPPL_ASSERT(to >= 0); return IntegerRange<T>(0, to); } template <typename T> IntegerRange<T> range(T from, T to) { SPCPPL_ASSERT(from <= to); return IntegerRange<T>(from, to); } template <typename T> ReversedIntegerRange<T> downrange(T from) { SPCPPL_ASSERT(from >= 0); return ReversedIntegerRange<T>(from, 0); } template <typename T> ReversedIntegerRange<T> downrange(T from, T to) { SPCPPL_ASSERT(from >= to); return ReversedIntegerRange<T>(from, to); } #include <utility> template <typename T> class Range { public: Range(T begin, T end) : begin_(std::move(begin)), end_(std::move(end)) { } T begin() { return begin_; } T end() { return end_; } private: T begin_; T end_; }; template <typename T> Range<T> make_range(T begin, T end) { return Range<T>(begin, end); } using namespace std; class OrderBook { public: int readInt(std::istream& in) { int res; in >> res; return res; } void outputInt(std::ostream& out, int s) { //out << s / 100 << '.' << s / 10 % 10 << s % 10; out << s; } void solve(std::istream& in, std::ostream& out) { int n, s; in >> n >> s; map <int, int> buy, sell; for (int i: range(n)) { char c; in >> c; int cost = readInt(in); int q; in >> q; if (c == 'B') { buy[cost] += q; } else { sell[cost] += q; } } while (sell.size() > s) { sell.erase(--sell.end()); } for (auto it: make_range(sell.rbegin(), sell.rend())) { out << 'S' << ' '; outputInt(out, it.first); out << ' ' << it.second << "\n"; } while (buy.size() > s) { buy.erase(buy.begin()); } for (auto it: make_range(buy.rbegin(), buy.rend())) { out << 'B' << ' '; outputInt(out, it.first); out << ' ' << it.second << "\n"; } } }; int main() { std::ios_base::sync_with_stdio(false); OrderBook solver; std::istream& in(std::cin); std::ostream& out(std::cout); in.tie(0); out << std::fixed; out.precision(20); solver.solve(in, out); return 0; }
573
A
Bear and Poker
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are $n$ players (including Limak himself) and right now all of them have bids on the table. $i$-th of them has bid with size $a_{i}$ dollars. Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
Any positive integer number can be factorized and written as $2^{a} \cdot 3^{b} \cdot 5^{c} \cdot 7^{d} \cdot ...$. We can multiply given numbers by $2$ and $3$ so we can increase $a$ and $b$ for them. So we can make all $a$ and $b$ equal by increasing them to the same big value (e.g. $100$). But we can't change powers of other prime numbers so they must be equal from the beginning. We can check it by diving all numbers from input by two and by three as many times as possible. Then all of them must be equal. Code Alternative solution is to calculate GCD of given numbers. Answer is "YES" iff we can get each number by multiplying GCD by $2$ and $3$. Otherwise, some number had different power of prime number other than $2$ and $3$.
[ "implementation", "math", "number theory" ]
1,300
#include<bits/stdc++.h> using namespace std; int t[1005*1005]; int main() { int n; scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%d", &t[i]); } int x = t[1]; for(int i = 2; i <= n; ++i) x = __gcd(x, t[i]); while(x % 2 == 0) x /= 2; while(x % 3 == 0) x /= 3; for(int i = 1; i <= n; ++i) { int two = 1, three = 1; while(t[i] % (two * 2) == 0) two *= 2; while(t[i] % (three * 3) == 0) three *= 3; if(x * two * three != t[i]) { puts("No"); return 0; } } puts("Yes"); return 0; }
573
B
Bear and Blocks
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built $n$ towers in a row. The $i$-th tower is made of $h_{i}$ identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time. Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.
In one operation the highest block in each tower disappears. So do all blocks above heights of neighbour towers. And all other blocks remain. It means that in one operation all heights change according to formula $h_{i} = min(h_{i - 1}, h_{i} - 1, h_{i + 1})$ where $h_{0} = h_{n + 1} = 0$. By using this formula two times we get height after two operations: $h_{i} = max(0, min(h_{i - 2}, h_{i - 1} - 1, h_{i} - 2, h_{i + 1} - 1, h_{i + 2}))$ and so on. From now I will omit $max(0, ...)$ part to make it easier to read. After $k$ operations we get $h_{i} = min(Left, Right)$ where $Left = min(h_{i - j} - (k - j)) = min(h_{i - j} + j - k)$ for $j\in\{0,1,\cdot\cdot,k\}$ and $Right$ is defined similarly. $h_{i}$ becomes zero when $Left$ or $Right$ becomes zero. And $Left$ becomes zero when $k = min(h_{i - j} + j)$ - we will find this value for all $i$. If you are now lost in this editorial, try to draw some test and analyze my formulas with it. For each $i$ we are looking for $min(h_{i - j} + j)$. We can iterate over $i$ from left to right keeping some variable $best$: We should to the same for $Right$ and take $min(Left, Right)$ for each $i$. Then final answer is maximum over answers for $i$. Code Div1C - Bear and Drawing Let's consider a tree already drawn on a strip of paper. Let's take first vertex on the left and last vertex on the right (in case of two vertices with the same $x$, we choose any of them). There is a path between them. Let's forget about vertices not on this path. A path divides a strip into 1D regions. What can be added to the main path? Only simple paths attached to it with one edge. So it can be one of the following structures - Y-letter or Line: Note that Y-letter can have long legs but its central part can have only one edge. How to check if given tree is a path + Y-letters + Lines? First, let's move from each leaf till we have vertex with degree at least $3$, marking vertices as deleted. We don't mark last vertex (that with degree at least $3$) as deleted but we increase his number of legs. Finally, for each not-deleted vertex we count his not-deleted neighbours for which $degree - min(legs, 2) > 1$ - otherwise this neighbour is start of Line or Y-letter. Each vertex on the main path can have at most two neighbours that also belong to the main path. There can be more neighbours but they must be in Lines or Y-letters - that's why we didn't count them. So answer is "No" iff for some vertex we counted more than two neighbours.
[ "binary search", "data structures", "dp", "math" ]
1,600
#include<bits/stdc++.h> using namespace std; const int nax = 1e5 + 5; vector<int> w[nax]; // leg is single/simple path ending with a leaf bool del[nax]; // vertices in legs are marked as deleted int legs[nax]; // numbers of legs starting in a vertex void dfs(int a, int par = 0) { if(w[a].size() <= 2) { del[a] = true; for(int b : w[a]) if(b != par) dfs(b, a); } } int main() { int n; scanf("%d", &n); for(int i = 0; i < n - 1; ++i) { int a, b; scanf("%d%d", &a, &b); w[a].push_back(b); w[b].push_back(a); } for(int a = 1; a <= n; ++a) if(w[a].size() == 1) dfs(a); for(int a = 1; a <= n; ++a) for(int b : w[a]) if(del[b]) legs[a] = min(legs[a]+1, 2); // at most two legs for(int a = 1; a <= n; ++a) if(!del[a]) { int cnt = 0; for(int b : w[a]) if(!del[b] && w[b].size() - legs[b] > 1) ++cnt; if(cnt > 2) { puts("No"); return 0; } } puts("Yes"); return 0; }
573
D
Bear and Cavalry
Would you want to fight against bears riding horses? Me neither. Limak is a grizzly bear. He is general of the dreadful army of Bearland. The most important part of an army is cavalry of course. Cavalry of Bearland consists of $n$ warriors and $n$ horses. $i$-th warrior has strength $w_{i}$ and $i$-th horse has strength $h_{i}$. Warrior together with his horse is called a unit. Strength of a unit is equal to multiplied strengths of warrior and horse. Total strength of cavalry is equal to sum of strengths of all $n$ units. Good assignment of warriors and horses makes cavalry truly powerful. Initially, $i$-th warrior has $i$-th horse. You are given $q$ queries. In each query two warriors swap their horses with each other. General Limak must be ready for every possible situation. What if warriors weren't allowed to ride their own horses? After each query find the maximum possible strength of cavalry if we consider assignments of all warriors to all horses that no warrior is assigned to his own horse (it can be proven that for $n ≥ 2$ there is always at least one correct assignment). Note that we can't leave a warrior without a horse.
Let's sort warriors and horses separately (by strength). For a moment we forget about forbidden assignments. Inversion is a pair of warriors that stronger one is assigned to weaker horse. We don't like inversions because it's not worse to assign strong warriors to strong horses: $A \cdot B + a \cdot b \ge A \cdot b + B \cdot a$ for $A \ge a$ and $B \ge b$. Note that repairing an inversion (by swapping assigned horses) decreases number of inversions - prove it by yourself (drawing a matching with intersections could be helpful). Without any restrictions the optimal matching is when we assign $i$-th warrior to $i$-th horse (indexed after sorting) - to get no inversions. Let's go back to version with forbidden connections. We have $n$ disjoint pairs which we can't use. We will prove that there exists an optimal assignment where (for all $i$) $i$-th warrior is assigned to $j$-th horse where $|i - j| \le 2$. Let's take an optimal assignment. In case of ties we take the one with the lowest number of inversions. Let's assume that $i$ is assigned to $i + 3$. There are at least $3$ warriors $j > i$ assigned to horses with indices lower than $i + 3$. So we have at least $3$ inversions with edge from $i$ to $i + 3$ (warriors on the left, horses on the right): Above, connection warrior-horse is an edge. Then inversions are intersections. Swapping horses for warriors $i$ and $j$ (where $j$ belongs so some red edge) would decrease number of inversions and it wouldn't decrease a score. We took an optimal assignment so it means that it's impossible to swap horses for them. Hence, for each red edge we can't change pair (black, read) into the following blue edges: So one of these blue edges is forbidden. Three red edges generate three pairs of blue edges and in each pair at least one blue edge must be forbidden. Note that all six blue edges are different. All blue edges are incident to warrior $i$ or to horse $i + 3$ but only one forbidden edge can be incident to warrior $i$ and only one forbidden edge can be incident to horse $i + 3$. We have at most two forbidden edges incident to them so it can't be true that three blue edges are forbidden. By cases analysis we can prove something more - that there can be only three possible types of connecting in an optimal assignment. First type: $i$ can be connected to $i$. Second: warrior $i$ with horse $i + 1$ and warrior $i + 1$ with horse $i$. Third: warriors $i$, $i + 1$ and $i + 2$ are connected with horses $i$, $i + 1$, $i + 2$. It gives us $O(nq)$ solution with calculating queries independently with $dp[i]$ defined as "what result can we get for assigning everything with indices lower than $i$?". To calculate $dp[i]$ we must know $dp[i - 3]$, $dp[i - 2]$ and $dp[i - 1]$. It wasn't intended solution because we can get better complexity. We can create a segment tree and for intervals we should keep info "result we can get for this interval with 0/1/2 first and 0/1/2 last elements removed". For an interval we keep matrix 3x3 and actualizing forbidden edge for single $i$ consists of: 1. calculating values of 3x3 matrix for a small interval with $i$ 2. actualizing a tree with $\log n$ times multiplying matrices Complexity is $O(q\log n\cdot3^{3})$.
[ "data structures", "divide and conquer", "dp" ]
3,000
null
573
E
Bear and Bowling
Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record! For rolling a ball one gets a score — an integer (maybe negative) number of points. Score for $i$-th roll is multiplied by $i$ and scores are summed up. So, for $k$ rolls with scores $s_{1}, s_{2}, ..., s_{k}$, total score is $\textstyle\sum_{i=1}^{k}i\cdot s_{i}$. Total score is $0$ if there were no rolls. Limak made $n$ rolls and got score $a_{i}$ for $i$-th of them. He wants to maximize his total score and he came up with an interesting idea. He will cancel some rolls, saying that something distracted him or there was a strong wind. Limak is able to cancel any number of rolls, maybe even all or none of them. Total score is calculated as if there were only non-canceled rolls. Look at the sample tests for clarification. What maximum total score can Limak get?
FIRST PART - greedy works We will add (take) elements to a subsequence one by one. Adding number $x$, when we have $k - 1$ taken numbers on the left, increases result by $k \cdot x + suf$ where $suf$ is sum of taken numbers on the right. Let's call this added value as the Quality of element $x$. We will prove correctness of the following greedy algorithm. We take element with the biggest Quality till there are no elements left. For every size of a subsequence (number of taken elements) we will get optimal score. (lemma) If $a_{i} > a_{j}$ and $i < j$, we won't take $a_{j}$ first. Proof. Let's consider a moment when we don't fulfill the lemma for the first time. If there are no taken numbers between $a_{i}$ and $a_{j}$, we have $Q_{i} = k \cdot a_{i} + suf > k \cdot a_{j} + suf = Q_{j}$ so $a_{i}$ is a better choice. For taken numbers between $a_{i}$ and $a_{j}$ - each number $x$ changes $Q_{i}$ by $x$ and $Q_{j}$ by $a_{j}$. We'll see that $x > a_{j}$ so $Q_{i}$ will remain greater than $Q_{j}$. If $a_{i} > x$, the lemma (fulfilled till now) says that $x$ wasn't taken before $a_{i}$ - it can't be true because $x$ is taken and $a_{i}$ is not. So indeed $x \ge a_{i} > a_{j}$. Let's assume that our greedy strategy is not correct. Let's consider first moment when we take some element $a_{j}$ and for some $s$ we can't get optimal subsequence with size $s$ by taking more elements (using any strategy). Let $A$ denote a set of elements taken before. So there is no way to add some more elements to set $A + a_{j}$ and achieve optimal score with size $s$. But it was possible just before taking $a_{j}$ so there is a subset of remaining elements $B$ that $|A + B| = s$ and set $A + B$ is the best among sets with size $s$. Note that $B$ can't be empty. (case 1 - $B$ contains at least one element on the left from $a_{j}$) Let $a_{i}$ denote last element from $B$ that $i < j$ (here "last" means "with the biggest $i$"). Our strategy wanted $a_{j}$ before elements from $B$ so we know from lemma that $a_{i} \le a_{j}$. It will turn out that replacing $a_{i}$ with $a_{j}$ (in set $A + B$) doesn't decrease the score so taking $a_{j}$ is acceptable. Note that replacing an element with another one doesn't change size of a set/subsequence. In moment of choosing $a_{j}$ it had the biggest quality so then $Q_{j} \ge Q_{i}$. Now in $A + B$ there are new elements, those in $B$. Let's imagine adding them to $A$ (without $a_{i}$ and $a_{j}$). Each new element $x$ on the right change both $Q_{i}$ and $Q_{j}$ by $x$. Elements on the left change $Q_{i}$ by $a_{i}$ and $Q_{j}$ by $a_{j}$ (note that $a_{i} \le a_{j}$). And there are no elements between $a_{i}$ and $a_{j}$. Now, taking $a_{i}$ would give us set $A + B$ but $Q_{j}$ remains not less than $Q_{i}$ so we can take $a_{j}$ instead. (case 2 - $B$ contains only elements on the right from $a_{j}$) Similarly, we can replace $a_{i}$ with closest $a_{j}$ from set $B$. As before, elements on the right change $Q_{i}$ and $Q_{j}$ by the same value. SECOND PART - how to implement it First, let's understand $O(n{\sqrt{n}}\log n)$ solution. We divide a sequence into $\sqrt{n}$ Parts. When choosing the best candidate in a Part, we want to forget about other Parts. It's enough to remember only $x$ and $suf$ - number of taken elements on the left (in previous Parts) and sum of elements on the right (in next Parts). $x$ affects choosing the best element in a Part, $suf$ doesn't (but we need this constant to add it to result for best candidate). For a Part we want to have hull with $\sqrt{n}$ linear functions of form $a_{i} \cdot x + b$. With binary search we can find the best element in $O({\sqrt{n}}\log n)$ and then construct new hull for this Part in $O({\sqrt{n}}\log n)$. We can remove $\log n$ from complexity. First, binary search can be replaced with pointers - for each Part initially we set a pointer at the beginning of Part. To find best candidate in Part, we slowly move pointer to the right (by one). Complexity is amortized $O(n{\sqrt{n}})$. And we can sort linear functions $a_{i} \cdot x + b$ by angle only once because value $a_{i}$ doesn't change - then constructing a hull is only $O({\sqrt{n}})$. Note that when rebuilding a hull, we must set pointer to the beginning of Part. So we have $O(n\log n+n{\sqrt{n}})$. There are other two correct lemmas to speed your solution up. We can take all positive numbers first (it's not so easy to prove). And we can stop when taken number doesn't increase score - next taken numbers won't increase score neither.
[ "data structures", "greedy" ]
3,200
#include<bits/stdc++.h> using namespace std; typedef long long ll; struct line { int a, id; ll b; line(int aa, ll bb, int idd) : a(aa), id(idd), b(bb) {} // does (this,B) intersect before (B,C) bool before(const line & B, const line & C) { // a*x + b = B.a*x + B.b // x * (a-B.a) = B.b-b // x * q1 = p1 ll p1 = B.b - b, p2 = C.b - b; int q1 = a - B.a, q2 = a - C.a; if(q1 < 0) { p1 *= -1; q1 *= -1; } if(q2 < 0) { p2 *= -1; q2 *= -1; } // x1 = p1/q1, x2 = p2/q2 return p1*q2 <= p2*q1; } ll f(int x) { return (ll) a * x + b; } }; struct hull { vector<int> a; // numbers from input vector<bool> taken; vector<line> w; // hull vector<int> order; int n; int pointer; int count; // number of taken elements ll sum; // sum of taken elements hull(){} hull(vector<int> aa) : a(aa) { count = sum = 0; n = (int) a.size(); taken.resize(n, false); for(int i = 0; i < n; ++i) order.push_back(i); // we find order only once, in constructor sort(order.begin(), order.end(), [&](int i, int j){ return a[i] < a[j]; }); build(); } void build() { // build hull pointer = 0; vector<ll> val(n); ll suf = sum; int cnt = 0; for(int i = 0; i < n; ++i) { if(taken[i]) { suf -= a[i]; ++cnt; } else val[i] = suf + (ll) a[i] * (cnt + 1); } vector<line> sorted; // linear sort using vector<int> order for(int i : order) if(!taken[i]) sorted.push_back(line(a[i], val[i], i)); w.clear(); for(line & C : sorted) { if(!w.empty() && w.back().a == C.a) { if(C.b <= w.back().b) continue; else w.pop_back(); } while((int) w.size() >= 2) { line & A = w[(int)w.size()-2]; line & B = w[(int)w.size()-1]; if(A.before(B, C)) break; w.pop_back(); } w.push_back(C); } } pair<ll, int> best(int before) { // find the best candidate, move pointer if(w.empty()) return make_pair(42LL, -1); while(pointer <= (int) w.size()-2 && w[pointer].f(before) < w[pointer+1].f(before)) ++pointer; assert(pointer < (int) w.size()); return make_pair(w[pointer].f(before), w[pointer].id); } void remove(int i) { // mark as taken assert(!taken[i]); taken[i] = true; sum += a[i]; ++count; build(); } } h[1005]; int a[1005*1005]; int main() { int n; scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", &a[i]); // divide into Parts with size sqrt(n) int s = max(1, int(sqrt(n))); for(int i = 0; i < n; i += s) { vector<int> w; for(int j = i; j < min(n, i+s); ++j) w.push_back(a[j]); h[i/s] = hull(w); } ll output = 0; // max(score) ll score = 0; // score for current set/subsequence while(true) { pair<ll,int> m = make_pair(42LL, -1); ll suf = 0; // sum of elements on the right int cnt = 0; // how many on the left for(int i = 0; i < n; i += s) suf += h[i/s].sum; for(int i = 0; i < n; i += s) { suf -= h[i/s].sum; // we ask this Part about max(ax+b) where x = cnt pair<ll, int> p = h[i/s].best(cnt); p.first += suf; // extra constant if(p.second != -1) if(m.second == -1 || p.first > m.first) m = make_pair(p.first, i+p.second); cnt += h[i/s].count; } if(m.second == -1) break; score += m.first; output = max(output, score); int i = m.second; h[i/s].remove(i-i/s*s); } printf("%lld\n", output); return 0; }
574
B
Bear and Three Musketeers
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are $n$ warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers. Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.
Warriors are vertices and "knowing each other" is an edge. We want to find connected triple of vertices with the lowest sum of degrees (and print $sum - 6$ because we don't want to count edges from one chosen vertex to another). Brute force is $O(n^{3})$. We iterate over all triples $a, b, c$ and consider them as musketeers. They must be connected by edges (they must know each other). If they are, then we consider sum of their degrees. We must notice that there is low limit for number of edges. So instead of iterating over triples of vertices we can iterate over edges and then iterate over third vertex. It gives us $O(n^{2} + nm)$ and it's intended solution. To check if third vertex is connected with other two, you should additionally store edges in 2D adjacency matrix. It's also possible to write it by adding "if" in right place in brute forces to get $O(n^{2} + nm)$.
[ "brute force", "dfs and similar", "graphs", "hashing" ]
1,500
#include<bits/stdc++.h> using namespace std; const int inf = 100000005; const int nax = 5005; int degree[nax]; bool t[nax][nax]; int main() { int n, m; scanf("%d%d", &n, &m); for(int i = 0; i < m; ++i) { int a, b; scanf("%d%d", &a, &b); t[a][b] = t[b][a] = true; degree[a]++; degree[b]++; } int result = inf; for(int i = 1; i <= n; ++i) for(int j = i + 1; j <= n; ++j) { // we are O(n^2) times here if(t[i][j]) { // we are O(m) times here for(int k = j + 1; k <= n; ++k) { // O(m * n) times here if(t[i][k] && t[j][k]) result = min(result, degree[i]+degree[j]+degree[k]); } } } if(result == inf) puts("-1"); else printf("%d\n", result - 6); return 0; }
576
A
Vasya and Petya's Game
Vasya and Petya are playing a simple game. Vasya thought of number $x$ between $1$ and $n$, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number $y$?". The game is played by the following rules: first Petya asks \textbf{all} the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of. Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers $y_{i}$, he should ask the questions about.
If Petya didn't ask $p^{k}$, where $p$ is prime and $k \ge 1$, he would not be able to distinguish $p^{k - 1}$ and $p^{k}$. That means, he should ask all the numbers $p^{k}$. It's easy to prove that this sequence actually guesses all the numbers from $1$ to $n$ The complexity is $O(N^{1.5})$ or $O(NloglogN)$ depending on primality test.
[ "math", "number theory" ]
1,500
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cmath>\n\n#define pb push_back\n#define pbk pop_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define all(x) (x).begin(), (x).end()\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\n#define len(a) ((int) (a).size())\n\n#ifdef CUTEBMAING\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define eprintf(...) 42\n#endif\n\nusing namespace std;\n\ntypedef long long int64;\ntypedef long double ld;\ntypedef unsigned long long lint;\n\nconst int inf = (1 << 30) - 1;\nconst int64 linf = (1ll << 62) - 1;\n\nint main() {\n\tint n; cin >> n;\n\tvector<int> is_prime(n + 1, true), primes;\n\tis_prime[0] = is_prime[1] = 0;\n\tfor (int i = 2; i * i <= n; i++) {\n\t\tif (is_prime[i]) {\n\t\t\tfor (int j = i * i; j <= n; j += i) {\n\t\t\t\tis_prime[j] = false;\n\t\t\t}\n\t\t}\n\t}\n\tvector<int> ans;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (is_prime[i]) {\n int q = 1;\n while (q <= n / i) {\n q *= i;\n ans.push_back(q);\n }\n\t\t}\n\t}\n\tcout << len(ans) << endl;\n\tfor (int i : ans) {\n\t printf(\"%d \", i);\n\t}\n\tputs(\"\");\n return 0;\n}"
576
B
Invariance of Tree
A tree of size $n$ is an undirected connected graph consisting of $n$ vertices without cycles. Consider some tree with $n$ vertices. We call a tree invariant relative to permutation $p = p_{1}p_{2}... p_{n}$, if for any two vertices of the tree $u$ and $v$ the condition holds: "vertices $u$ and $v$ are connected by an edge if and only if vertices $p_{u}$ and $p_{v}$ are connected by an edge". You are given permutation $p$ of size $n$. Find some tree size $n$, invariant relative to the given permutation.
Let's look at the answer. It's easy to notice, that centers of that tree must turn into centers after applying the permutation. That means, permutation must have cycle with length $1$ or $2$ since there're at most two centers. If permutation has cycle with length $1$, we can connect all the other vertices to it. For example, let's look at the permutation $(4, 2, 1, 3)$. $2$ is a cycle with length $2$, so let's connect all the other vertices to it. The resulting tree edges would be $(1, 2)$, $(2, 3)$, $(2, 4)$. If answer has two centers, let's remove the edge between them. The tree will split into two connected parts. It's easy to see that they will turn into each other after applying permutation. That means, all cycles should be even. It's easy to come up with answer with these restrictions. Let's connect vertices from the cycles with length $2$. Then, let's connect vertices with odd position in cycles to first of these and vetices with even cycles to second one. For example, let's consider permutation $(6, 5, 4, 3, 1, 2)$. There are two cycles: $(3, 4)$ and $(1, 6, 2, 5)$. We add edge $(3, 4)$, all other vertices we connect to these two, obtaining edges $(1, 3)$, $(6, 4)$, $(2, 3)$, $(5, 4)$. The complexity is $O(N)$.
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
2,100
"#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#include <algorithm>\n#include <numeric>\n\n#include <vector>\n#include <set>\n#include <map>\n#include <bitset>\n#include <deque>\n\n#include <ctime>\n#include <cmath>\n#include <cstdlib>\n#include <cstdio>\n#include <cassert>\n\n#define pb push_back\n#define pbk pop_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define all(x) (x).begin(), (x).end()\n#define len(a) ((int) (a).size())\n#define endl '\\n'\n\n#ifdef CUTEBMAING\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define eprintf(...) ({})\n#endif\n\nusing namespace std;\n\ntypedef long long int64;\ntypedef long double ld;\ntypedef unsigned long long lint;\n\nconst int inf = (1 << 30) - 1;\nconst int64 linf = (1ll << 62) - 1;\nconst int N = 1e6;\n\nint n;\nint p[N];\n\nint division[2][N];\nint dln[2];\nbool u[N];\n\nint main(){\n\tcin >> n;\n\tfor (int i = 0; i < n; i++){\n\t\tscanf(\"%d\", &p[i]);\n\t\tp[i]--;\n\t}\n\tint index1 = -1, index2 = -1;\n\tfor (int i = 0; i < n; i++){\n\t\tif (p[i] == i)\n\t\t\tindex1 = i;\n\t\tif (p[p[i]] == i)\n\t\t\tindex2 = i;\n\t}\n\tif (index1 != -1){\n\t\tputs(\"YES\");\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tif (index1 != i)\n\t\t\t\tprintf(\"%d %d\\n\", index1 + 1, i + 1);\n\t\treturn 0;\n\t}\n\tif (index2 != -1){\n\t\tbool flag = true;\n\t\tdln[0] = dln[1] = 0;\n\t\tfill_n(u, n, 0);\n\t\tu[index2] = u[p[index2]] = 1;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tif (!u[i]){\n\t\t\t\tu[i] = 1;\n\t\t\t\tdivision[0][dln[0]++] = i;\n\t\t\t\tint curI = p[i], step = 1;\n\t\t\t\twhile (curI != i){\n\t\t\t\t\tu[curI] = 1;\n\t\t\t\t\tdivision[step][dln[step]++] = curI;\n\t\t\t\t\tstep ^= 1;\n\t\t\t\t\tcurI = p[curI];\n\t\t\t\t}\n\t\t\t\tif (step == 1){\n\t\t\t\t\tflag = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\tif (!flag){\n\t\t\tputs(\"NO\");\n\t\t\treturn 0;\n\t\t}\n\t\tputs(\"YES\");\n\t\tprintf(\"%d %d\\n\", index2 + 1, p[index2] + 1);\n\t\tfor (int i = 0; i < dln[0]; i++)\n\t\t\tprintf(\"%d %d\\n\", index2 + 1, division[0][i] + 1);\n\t\tfor (int i = 0; i < dln[1]; i++)\n\t\t\tprintf(\"%d %d\\n\", p[index2] + 1, division[1][i] + 1);\n\t\treturn 0;\n\t}\n\tputs(\"NO\");\n\treturn 0;\n}"
576
C
Points on Plane
On a plane are $n$ points ($x_{i}$, $y_{i}$) with integer coordinates between $0$ and $10^{6}$. The distance between the two points with numbers $a$ and $b$ is said to be the following value: $\operatorname{dist}(a,b)=|x_{a}-x_{b}|+|y_{a}-y_{b}|$ (the distance calculated by such formula is called Manhattan distance). We call a hamiltonian path to be some permutation $p_{i}$ of numbers from $1$ to $n$. We say that the length of this path is value $\sum_{i=1}^{n-1}\mathrm{dist}(p_{i},p_{i+1})$. Find some hamiltonian path with a length of no more than $25 × 10^{8}$. Note that you do not have to minimize the path length.
Let's split rectangle $10^{6} \times 10^{6}$ by vertical lines into $1000$ rectangles $10^{3} \times 10^{6}$. Let's number them from left to right. We're going to pass through points rectangle by rectangle. Inside the rectangle we're going to pass the points in increasing order of $y$-coordinate if the number of rectangle is even and in decreasing if it's odd. Let's calculate the maximum length of such a way. The coordinates are independent. By $y$-coordinate we're passing 1000 rectangles from $0$ to $10^{6}$, $10^{9}$ in total. By $x$-coordinate we're spending $1000$ to get to the next point of current rectangle and $2000$ to get to next rectangle. That means, $2 * 10^{9} + 2000000$ in total, which perfectly fits. The complexity is $O(n * log(n))$
[ "constructive algorithms", "divide and conquer", "geometry", "greedy", "sortings" ]
2,100
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cmath>\n\n#define pb push_back\n#define pbk pop_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define all(x) (x).begin(), (x).end()\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\n#define len(a) ((int) (a).size())\n\n#ifdef CUTEBMAING\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define eprintf(...) 42\n#endif\n\nusing namespace std;\n\ntypedef long long int64;\ntypedef long double ld;\ntypedef unsigned long long lint;\n\nconst int inf = (1 << 30) - 1;\nconst int64 linf = (1ll << 62) - 1;\nconst int C = 1000;\n\nint main() {\n\tint n; cin >> n;\n\tvector<pair<pair<int, int>, int>> points(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tscanf(\"%d%d\", &points[i].fs.fs, &points[i].fs.sc);\n\t\tpoints[i].sc = i;\n\t\tpoints[i].fs.fs /= C;\n\t}\n\tsort(all(points), [](const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b) {\n\t return a.fs.fs < b.fs.fs || (a.fs.fs == b.fs.fs && (a.fs.fs % 2 == 0 ? (a.fs.sc < b.fs.sc) : (a.fs.sc > b.fs.sc)));\n\t});\n\tfor (auto i : points) {\n\t\tprintf(\"%d \", i.sc + 1);\n\t}\n\tputs(\"\");\n return 0;\n}"
576
D
Flights for Regular Customers
In the country there are exactly $n$ cities numbered with positive integers from $1$ to $n$. In each city there is an airport is located. Also, there is the only one airline, which makes $m$ flights. Unfortunately, to use them, you need to be a regular customer of this company, namely, you have the opportunity to enjoy flight $i$ from city $a_{i}$ to city $b_{i}$ only if you have already made at least $d_{i}$ flights before that. Please note that flight $i$ flies exactly from city $a_{i}$ to city $b_{i}$. It can not be used to fly from city $b_{i}$ to city $a_{i}$. An interesting fact is that there may possibly be recreational flights with a beautiful view of the sky, which begin and end in the same city. You need to get from city $1$ to city $n$. Unfortunately, you've never traveled by plane before. What minimum number of flights you have to perform in order to get to city $n$? Note that the same flight can be used multiple times.
Let's optimize the first solution that comes to mind: $O(m * d_{max})$, let's calculate $can[t][v]$ - can we get to the vertice $v$, while passing exactly $t$ edges. Now, it's easy to find out that the set of edges we are able to go through changed only $m$ times. Let's sort these edges in increasing order of $d_{i}$, that means for each $i$ $d_{i} \le d_{i + 1}$. Let's calculate $can[t][v]$ only for $t = d_{i}$. We can calculate $can[d_{i + 1}]$ using $can[d_{i}]$ by raising the adjacency matrix to the $d_{i + 1} - d_{i}$ power and applying it to $can[d_{i}]$. Next step is to fix an edge with maximal $d_{i}$ on our shortest path, let it be $i$. We know all the vertices we can be at moment $d_{i}$, so we need to calculate the shortest path to $n - 1$ using edges we can go through. We can even use Floyd algorithm to calculate that. The complexity of this solution is $O(m * n^{3} * log(d_{max}))$ and it's not enough. Next observation is that adjacency matrix contains only zeroes or ones, so we can multiply these matrixes using bitsets in $O(n^{3} / 32)$. This makes complexity $O(m * n^{3} * log(d_{max}) / 32)$, which gets accepted.
[ "dp", "matrices" ]
2,700
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cmath>\n\n#define pb push_back\n#define pbk pop_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define all(x) (x).begin(), (x).end()\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\n#define len(a) ((int) (a).size())\n\n#ifdef CUTEBMAING\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define eprintf(...) 42\n#endif\n\nusing namespace std;\n\ntypedef long long int64;\ntypedef long double ld;\ntypedef unsigned long long lint;\n\nconst int inf = (1 << 30) - 1;\nconst int64 linf = (1ll << 62) - 1;\nconst int N = 160;\nconst int K = 30;\n\nstruct edges {\n\tint u, v;\n};\n\nint n, m;\nmap<int, vector<edges>> g;\nvector<pair<int, vector<edges>>> events;\n\nbitset<N> mat[K][N];\n\nbitset<N> temp[N];\n\nvoid mul(bitset<N> a[N], bitset<N> b[N], bitset<N> c[N]) {\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\ttemp[j].set(i, b[i].test(j));\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tc[i].set(j, (a[i] & temp[j]).any());\n\t\t}\n\t}\n}\n\nint dist[N][N];\nbool cur[N], ncur[N];\n\nvoid apply(bitset<N> a[N]) {\n\tfill_n(ncur, n, 0);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (cur[i]) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tif (a[i].test(j)) {\n\t\t\t\t\tncur[j] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tmemcpy(cur, ncur, sizeof(bool) * n);\n}\n\nint main() {\n\tcin >> n >> m;\n\tfor (int i = 0; i < m; i++) {\n\t\tint a, b, d; cin >> a >> b >> d;\n\t\tg[d].pb({a - 1, b - 1});\n\t}\n\tg[0].pb({n - 1, n - 1});\n\tg[inf].pb({n - 1, n - 1});\n\tevents = vector<pair<int, vector<edges>>>(all(g));\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tdist[i][j] = inf;\n\t\t}\n\t\tdist[i][i] = 0;\n\t\tmat[0][i].reset();\n\t}\n\tcur[0] = 1;\n\tint ans = inf;\n\tfor (int i = 0; i < len(events) - 1; i++) {\n\t\tint curTime = events[i].fs, nextTime = events[i + 1].fs;\n\t\tfor (edges e : events[i].sc) {\n\t\t\tmat[0][e.u].set(e.v, true);\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tfor (int z = 0; z < n; z++) {\n\t\t\t\t\tdist[j][z] = min(dist[j][z], dist[j][e.u] + dist[e.v][z] + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (cur[i]) {\n\t\t\t\tans = min(ans, curTime + dist[i][n - 1]);\n\t\t\t}\n\t\t}\n\t\tfor (int j = 1; j < K; j++) {\n\t\t\tmul(mat[j - 1], mat[j - 1], mat[j]);\n\t\t}\n\t\tint delta = nextTime - curTime;\n\t\tfor (int j = K - 1; j >= 0; j--) {\n\t\t\tif (delta >= (1 << j)) {\n\t\t\t\tapply(mat[j]);\n\t\t\t\tdelta -= (1 << j);\n\t\t\t}\n\t\t}\n\t}\n\tif (ans >= inf) {\n\t\tcout << \"Impossible\" << endl;\n\t} else {\n\t\tcout << ans << endl;\n\t\teprintf(\"ans = %d\\n\", ans);\n\t}\n return 0;\n}"
576
E
Painting Edges
Note the unusual memory limit for this problem. You are given an undirected graph consisting of $n$ vertices and $m$ edges. The vertices are numbered with integers from $1$ to $n$, the edges are numbered with integers from $1$ to $m$. Each edge can be unpainted or be painted in one of the $k$ colors, which are numbered with integers from $1$ to $k$. Initially, none of the edges is painted in any of the colors. You get queries of the form "Repaint edge $e_{i}$ to color $c_{i}$". At any time the graph formed by the edges of the same color must be bipartite. If after the repaint this condition is violated, then the query is considered to be invalid and edge $e_{i}$ keeps its color. Otherwise, edge $e_{i}$ is repainted in color $c_{i}$, and the query is considered to valid. Recall that the graph is called bipartite if the set of its vertices can be divided into two parts so that no edge connected vertices of the same parts. For example, suppose you are given a triangle graph, that is a graph with three vertices and edges $(1, 2)$, $(2, 3)$ and $(3, 1)$. Suppose that the first two edges are painted color $1$, and the third one is painted color $2$. Then the query of "repaint the third edge in color $1$" will be incorrect because after its execution the graph formed by the edges of color $1$ will not be bipartite. On the other hand, it is possible to repaint the second edge in color $2$. You receive $q$ queries. For each query, you should either apply it, and report that the query is valid, or report that the query is invalid.
Let's solve an easier task first: independent of bipartivity, the color of edge changes. Then we could write a solution, which is pretty similar to solution of Dynamic Connectivity Offline task in $O(nlog^{2n})$. Let's consider only cases, where edges are not being deleted from the color graph. Then, we could use DSU with storing parity of the way to the parent along with parent. Now we can find parity of the path to the root by jumping through parents and xoring the parities. Also, we can connect two components by accurately calculating the parity of the path from one root to another. Now edges are being deleted. For each edge and each color we know the segments of requests, when this edge will be in the graph of specified color. Let's build a segment tree on requests, in each vertex of the tree we store list of edges which exist on the subsegment. Every segment will be split into $log$ parts, so, totally there would be $n * log$ small parts. Now we can dfs this segment tree with DSU. We get inside the vertex, apply all the requests inside it, go through the children and revert DSU to initial state. We also answer requests in leafs of the segment tree. Let's return to initial task. We can't use this technique, because we don't know the exact segments of edge existence. Instead, let's do following. Initially we add each edge right until the first appearance of this edge in requests. Now, when we're in some leaf, we found out which color this edge would be right until the next appearance of this edge. So, let's update this edge on that segment. For each leaf we're going to make an update at most once, so the complexity is $O(nlog^{2}n)$.
[ "binary search", "data structures" ]
3,300
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cmath>\n\n#define pb push_back\n#define pbk pop_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define all(x) (x).begin(), (x).end()\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\n#define len(a) ((int) (a).size())\n\n#ifdef CUTEBMAING\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define eprintf(...) 42\n#endif\n\nusing namespace std;\n\ntypedef long long int64;\ntypedef long double ld;\ntypedef unsigned long long lint;\n\nconst int inf = (1 << 30) - 1;\nconst int64 linf = (1ll << 62) - 1;\nconst int N = 5e5 + 100;\nconst int K = 50;\n\nstruct cooldsu {\n\tint parent[N], rank[N], parity[N];\n\tint flag = 0;\n\tvector<pair<int*, int>> changes;\n\n\tvoid init(int n) {\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tparent[i] = i, rank[i] = 0, parity[i] = 0;\n\t\t}\n\t}\n\n\tint size() { return changes.size(); }\n\n\tvoid set(int *a, int b) { changes.push_back(mp(a, *a)), *a = b; }\n\n\tvoid revert(int len) {\n\t\twhile (len(changes) > len) {\n\t\t\t*changes.back().fs = changes.back().sc, changes.pop_back();\n\t\t}\n\t}\n\n\tpair<int, int> findSetAndParity(int v) {\n\t\tint curParity = 0;\n\t\twhile (parent[v] != v) {\n\t\t\tcurParity ^= parity[v], v = parent[v];\n\t\t}\n\t\treturn mp(v, curParity);\n\t}\n\n\tvoid unite(int a, int b) {\n\t\tpair<int, int> pa = findSetAndParity(a), pb = findSetAndParity(b);\n\t\tif (pa.fs == pb.fs) {\n\t\t\tif (!flag && pa.sc == pb.sc) {\n\t\t\t\tset(&flag, 1);\n\t\t\t}\n\t\t\treturn ;\n\t\t}\n\t\tif (rank[pa.fs] == rank[pb.fs]) {\n\t\t\tset(rank + pa.fs, rank[pa.fs] + 1);\n\t\t}\n\t\tif (rank[pa.fs] > rank[pb.fs]) {\n\t\t\tswap(pa, pb);\n\t\t}\n\t\tset(parent + pa.fs, pb.fs), set(parity + pa.fs, pa.sc ^ pb.sc ^ 1);\n\t}\n};\n\nvector<pair<int, int>> rmq[N * 4 + 100];\n\ncooldsu dsu[K];\n\nint n, m, k, q;\nint a[N], b[N];\nint e[N], c[N];\nint nextRequest[N], last[N];\nint curColor[N];\n\nvoid update(int i, int ll, int rr, int l, int r, const pair<int, int> &add) {\n\tif (ll > r || rr < l) {\n\t\treturn ;\n\t}\n\tif (l <= ll && rr <= r) {\n\t\treturn void (rmq[i].push_back(add));\n\t}\n\tupdate(i * 2, ll, (ll + rr) / 2, l, r, add);\n\tupdate(i * 2 + 1, (ll + rr) / 2 + 1, rr, l, r, add);\n}\n\nvoid solve(int i, int l, int r) {\n\tvector<int> ln(len(rmq[i]));\n\tfor (int j = 0; j < len(ln); j++) {\n\t\tln[j] = len(dsu[rmq[i][j].sc]);\n\t}\n\tfor (auto upd : rmq[i]) {\n\t\tdsu[upd.sc].unite(a[upd.fs], b[upd.fs]);\n\t}\n\tif (l == r) {\n\t\tint edge = e[l], color = c[l];\n\t\tint u = a[edge], v = b[edge];\n\t\tpair<int, int> a = dsu[color].findSetAndParity(u), b = dsu[color].findSetAndParity(v);\n\t\tif (a != b) {\n\t\t\tputs(\"YES\");\n\t\t\tupdate(1, 0, q - 1, l + 1, nextRequest[l] - 1, mp(edge, color));\n\t\t\tcurColor[edge] = color;\n\t\t} else {\n\t\t\tputs(\"NO\");\n\t\t\tif (curColor[edge] != -1) {\n\t\t\t\tupdate(1, 0, q - 1, l + 1, nextRequest[l] - 1, mp(edge, curColor[edge]));\n\t\t\t}\n\t\t}\n\t} else {\n\t\tsolve(i * 2, l, (l + r) / 2);\n\t\tsolve(i * 2 + 1, (l + r) / 2 + 1, r);\n\t}\n\tfor (int j = 0; j < len(ln); j++) {\n\t\tdsu[rmq[i][j].sc].revert(ln[j]);\n\t}\n}\n\nint main() {\n\tcin >> n >> m >> k >> q;\n\tfor (int i = 0; i < k; i++) {\n\t\tdsu[i].init(n);\n\t}\n\tfor (int i = 0; i < m; i++) {\n\t\tscanf(\"%d%d\", &a[i], &b[i]), a[i]--, b[i]--;\n\t\tcurColor[i] = -1;\n\t}\n\tfor (int i = 0; i < q; i++) {\n\t\tscanf(\"%d%d\", &e[i], &c[i]), e[i]--, c[i]--;\n\t}\n\tfill_n(last, m, inf);\n\tfor (int i = q - 1; i >= 0; i--) {\n\t\tnextRequest[i] = last[e[i]];\n\t\tlast[e[i]] = i;\n\t}\n\tsolve(1, 0, q - 1);\n return 0;\n}"
577
A
Multiplication Table
Let's consider a table consisting of $n$ rows and $n$ columns. The cell located at the intersection of $i$-th row and $j$-th column contains number $i × j$. The rows and columns are numbered starting from 1. You are given a positive integer $x$. Your task is to count the number of cells in a table that contain number $x$.
It's easy to see that number $x$ can appear in column $i$ only once - in row $x / i$. For every column $i$, let's check that $x$ divides $i$ and $x / i \le n$. If all requirements are met, we'll update the answer. The complexity is $O(n)$
[ "implementation", "number theory" ]
1,000
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cmath>\n\n#define pb push_back\n#define pbk pop_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define all(x) (x).begin(), (x).end()\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\n#define len(a) ((int) (a).size())\n\n#ifdef CUTEBMAING\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define eprintf(...) 42\n#endif\n\nusing namespace std;\n\ntypedef long long int64;\ntypedef long double ld;\ntypedef unsigned long long lint;\n\nconst int inf = (1 << 30) - 1;\nconst int64 linf = (1ll << 62) - 1;\n\nint main() {\n\tint n, x; cin >> n >> x;\n\tint ans = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (x % i == 0 && x / i <= n) {\n\t\t\tans++;\n\t\t}\n\t}\n\tcout << ans << endl;\n return 0;\n}"
577
B
Modulo Sum
You are given a sequence of numbers $a_{1}, a_{2}, ..., a_{n}$, and a number $m$. Check if it is possible to choose a non-empty subsequence $a_{ij}$ such that the sum of numbers in this subsequence is divisible by $m$.
Let's consider two cases: $n > m$ and $n \le m$. If $n > m$, let's look at prefix sums. By pigeonhole principle, there are two equals sums modulo $m$. Assume $S_{lmodm} = S_{rmodm}$. Then the sum on segment $[l + 1, r]$ equals zero modulo $m$, that means the answer is definitely "YES". If $n \le m$, we'll solve this task using dynamic programming in $O(m^{2})$ time. Assume $can[i][r]$ means if we can achieve the sum equal to $r$ modulo $m$ using only first $i - 1$ items. The updates in this dynamic programming are obvious: we either take number $a_{i}$ and go to the state $can[i + 1][(r + a_{i}) mod m]$ or not, then we'll get to the state $can[i + 1][r]$. The complexity is $O(m^{2})$.
[ "combinatorics", "data structures", "dp", "two pointers" ]
1,900
"#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <vector>\n#include <set>\n#include <bitset>\n#include <map>\n#include <deque>\n#include <string>\n\n#include <algorithm>\n#include <numeric>\n\n#include <cstdio>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cmath>\n\n#define pb push_back\n#define pbk pop_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define all(x) (x).begin(), (x).end()\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\n#define len(a) ((int) (a).size())\n\n#ifdef CUTEBMAING\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define eprintf(...) 42\n#endif\n\nusing namespace std;\n\ntypedef long long int64;\ntypedef long double ld;\ntypedef unsigned long long lint;\n\nconst int inf = (1 << 30) - 1;\nconst int64 linf = (1ll << 62) - 1;\n\nint main() {\n\tint n, x; cin >> n >> x;\n\tint ans = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (x % i == 0 && x / i <= n) {\n\t\t\tans++;\n\t\t}\n\t}\n\tcout << ans << endl;\n return 0;\n}"
578
A
A Problem about Polyline
There is a polyline going through points $(0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ...$. We know that the polyline passes through the point $(a, b)$. Find minimum positive value $x$ such that it is true or determine that there is no such $x$.
If point ($a$,$b$) is located on the up slope/ down slope of this polyline. Then the polyline will pass the point ($a - b$,$0$)/($a + b$,$0$).(we call $(a - b)$ or $(a + b)$ as $c$ afterwards) And we can derive that $c / (2 * x)$ should be a positive integer. Another condition we need to satisfy is that $x$ must be larger than or equal to $b$. It's easy to show that when those two conditions are satisfied, then the polyline will pass the point ($a$,$b$). Formally speaking in math : Let $c / (2 * x) = y$ Then we have $x = c / (2 * y) \ge b$ and we want to find the maximum integer $y$. After some more math derivation, we can get the answer is $[\mathrm{III}\left({\frac{a-b}{2s[}},{\frac{d+b}{2s[}}\right),\,{\frac{d+b}{2s[}}\right)$. Besides, the only case of no solution is when $a < b$. In fact, $\frac{a-b}{2*\left[{\frac{a-b}{2*b}}\right]}$ always dosn't exist or larger than $\frac{a+b}{2*\left[{\frac{a+b}{2*b}}\right]}$.
[ "geometry", "math" ]
1,700
#include <bits/stdc++.h> typedef long long LL; using namespace std; int main(){ LL a,b; cin>>a>>b; if(a<b)puts("-1"); else printf("%.12f\n",(a+b)/(2.*((a+b)/(2*b)))); return 0; }
578
B
"Or" Game
You are given $n$ numbers $a_{1}, a_{2}, ..., a_{n}$. You can perform at most $k$ operations. For each operation you can multiply one of the numbers by $x$. We want to make $a_{1}\mid a_{2}\mid\dots\mid a_{n}$ as large as possible, where denotes the bitwise OR. Find the maximum possible value of $a_{1}\mid a_{2}\mid\ldots\mid a_{n}$ after performing at most $k$ operations optimally.
We can describe a strategy as multiplying $a_{i}$ by $x$ $t_{i}$ times so $a_{i}$ will become $b_{i} = a_{i} * x^{ti}$ and sum of all $t_{i}$ will be equals to $k$. The fact is there must be a $t_{i}$ equal to $k$ and all other $t_{i}$ equals to $0$. If not, we can choose the largest number $b_{j}$ in sequence $b$, and change the strategy so that $t_{j} = k$ and all other $t_{j} = 0$. The change will make the highest bit $1$ of $b_{j}$ become higher so the $or$-ed result would be higher. After knowing the fact, We can iterator all number in sequence a and multiply it by $x^{k}$ and find the maximum value of our target between them. There are several method to do it in lower time complexity. You can check the sample code we provide.(I believe you can understand it quickly.)
[ "brute force", "greedy" ]
1,700
#include<cstdio> #include<algorithm> using namespace std; const int SIZE = 2e5+2; long long a[SIZE],prefix[SIZE],suffix[SIZE]; int main(){ int n,k,x; scanf("%d%d%d", &n, &k, &x); long long mul=1; while(k--) mul *= x; for(int i = 1; i <= n; i++) scanf("%I64d", &a[i]); for(int i = 1; i <= n; i++) prefix[i] = prefix[i-1] | a[i]; for(int i = n; i > 0; i--) suffix[i] = suffix[i+1] | a[i]; long long ans = 0; for(int i= 1; i <= n; i++) ans = max(ans, prefix[i-1] | (a[i] * mul) | suffix[i+1]); printf("%I64d\n",ans); }
578
C
Weakness and Poorness
You are given a sequence of n integers $a_{1}, a_{2}, ..., a_{n}$. Determine a real number $x$ such that the weakness of the sequence $a_{1} - x, a_{2} - x, ..., a_{n} - x$ is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence. The poorness of a segment is defined as the absolute value of sum of the elements of segment.
Let $s(i,j)=\sum_{k=i}^{j}(a_{k}-x)$, we can write down the definition of poorness formally as . It's easy to see that $A$ is a strictly decreasing function of $x$, and $B$ is a strictly increasing function of x. Thus the minimum of $max(A, B)$ can be found using binary or ternary search. The time complexity is $O(n\log C)$, Now here give people geometry viewpoint of this problem: let $b_{i}=\sum_{k=1t o i}a_{i}$ We plot $n + 1$ straight line $y = i * x + b_{i}$ in the plane for $i$ from $0$ to $n$. We can discover when you are given $x$. The weakness will be (y coordinator of highest line at x) - (y coordinator of lowest line at x). So we only need to consider the upper convex hull and the lower convex hull of all lines. And the target x value will be one of the intersection of these convex hull. Because you can get these line in order of their slope value. we can use stack to get the convex hulls in O(n).
[ "ternary search" ]
2,000
#include <bits/stdc++.h> typedef long long LL; using namespace std; const int SIZE = 2e5+10; int a[SIZE]; int up_stk[SIZE],down_stk[SIZE]; int Un=1,Dn=1; LL compare(LL x,LL y,LL z,LL w){return (a[x]-a[y])*(w-z)-(a[z]-a[w])*(y-x);} double get_x(int x,int y){return (a[x]-a[y])*1./(y-x);} double get_y(double v,int x){return x*v+a[x];} int main(){ int n; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); a[i]+=a[i-1]; while(Un>1&&compare(up_stk[Un-1],i,up_stk[Un-1],up_stk[Un-2])>=0)Un--; up_stk[Un++]=i; while(Dn>1&&compare(down_stk[Dn-1],i,down_stk[Dn-1],down_stk[Dn-2])<=0)Dn--; down_stk[Dn++]=i; } reverse(down_stk,down_stk+Dn); int it1=0,it2=0; double an=1e18; while(it1+1<Dn||it2+1<Un){ if(it2+1>=Un||(it1+1<Dn&&compare(down_stk[it1],down_stk[it1+1],up_stk[it2+1],up_stk[it2])<=0)){ double x=get_x(down_stk[it1],down_stk[it1+1]); an=min(an,get_y(x,up_stk[it2])-get_y(x,down_stk[it1])); it1++; } else{ double x=get_x(up_stk[it2],up_stk[it2+1]); an=min(an,get_y(x,up_stk[it2])-get_y(x,down_stk[it1])); it2++; } } printf("%.15f\n",an); return 0; }
578
D
LCS Again
You are given a string $S$ of length $n$ with each character being one of the first $m$ lowercase English letters. Calculate how many different strings $T$ of length $n$ composed from the first $m$ lowercase English letters exist such that the length of LCS (longest common subsequence) between $S$ and $T$ is $n - 1$. Recall that LCS of two strings $S$ and $T$ is the longest string $C$ such that $C$ both in $S$ and $T$ as a subsequence.
Followings are solution in short. Considering the LCS dp table $lcs[x][y]$ which denotes the LCS value of first $x$ characters of $S$ and first $y$ characters of $T$. If we know $lcs[n][n] = n - 1$, then we only concern values in the table which $abs(x - y) \le 1$ and all value of $lcs[x][y]$ must be $min(x, y)$ or $min(x, y) - 1$. So each row contains only $8$ states(In fact,three states among these states will never be used), we can do dp on it row by row with time complexity $O(n)$. There is another not dp method. You can refer this comment.
[ "dp", "greedy" ]
2,700
#include <bits/stdc++.h> #define SZ(X) ((int)(X).size()) #define ALL(X) (X).begin(), (X).end() #define REP(I, N) for (int I = 0; I < (N); ++I) #define REPP(I, A, B) for (int I = (A); I < (B); ++I) #define RI(X) scanf("%d", &(X)) #define RII(X, Y) scanf("%d%d", &(X), &(Y)) #define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z)) #define DRI(X) int (X); scanf("%d", &X) #define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y) #define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z) #define RS(X) scanf("%s", (X)) #define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0) #define MP make_pair #define PB push_back #define MS0(X) memset((X), 0, sizeof((X))) #define MS1(X) memset((X), -1, sizeof((X))) #define LEN(X) strlen(X) #define PII pair<int,int> #define VPII vector<pair<int,int> > #define PLL pair<long long,long long> #define F first #define S second typedef long long LL; using namespace std; const int MOD = 1e9+7; const int SIZE = 1e5+10; // template end here LL dp[SIZE][8]; char s[SIZE]; int get_bit(int x,int v){return (x>>v)&1;} int main(){ DRII(n,m); RS(s+1); REPP(i,1,n+1)s[i]-='a'; s[n+1]=-1; REP(i,m){ int state=1; if(i==s[1])state|=2; if(i==s[1]||i==s[2])state|=4; dp[1][state]++; } REPP(i,2,n+1){ REP(j,8){ int d[4]={i-3+get_bit(j,0),i-2+get_bit(j,1),i-2+get_bit(j,2)}; REP(k,m){ int d2[4]={}; REPP(l,1,4){ if(s[i-2+l]==k)d2[l]=d[l-1]+1; else d2[l]=max(d2[l-1],d[l]); } if(d2[1]>=i-2&&min(d2[2],d2[3])>=i-1)dp[i][(d2[1]-(i-2))|((d2[2]-(i-1))<<1)|((d2[3]-(i-1))<<2)]+=dp[i-1][j]; } } } printf("%lld\n",dp[n][0]+dp[n][1]+dp[n][4]+dp[n][5]); return 0; }
578
E
Walking!
There is a sand trail in front of Alice's home. In daytime, people walk over it and leave a footprint on the trail for their every single step. Alice cannot distinguish the order of the footprints, but she can tell whether each footprint is made by left foot or right foot. Also she's certain that all people are walking by alternating left foot and right foot. For example, suppose that one person walked through the trail and left some footprints. The footprints are RRLRL in order along the trail ('R' means right foot and 'L' means left foot). You might think the outcome of the footprints is strange. But in fact, some steps are resulting from walking backwards! There are some possible order of steps that produce these footprints such as $1 → 3 → 2 → 5 → 4$ or $2 → 3 → 4 → 5 → 1$ (we suppose that the distance between two consecutive steps can be arbitrarily long). The number of backward steps from above two examples are $2$ and $1$ separately. Alice is interested in these footprints. Whenever there is a person walking trough the trail, she takes a picture of all these footprints along the trail and erase all of them so that next person will leave a new set of footprints. We know that people walk by alternating right foot and left foot, but we don't know if the first step is made by left foot or right foot. Alice wants to know the minimum possible number of backward steps made by a person. But it's a little hard. Please help Alice to calculate it. You also need to construct one possible history of these footprints.
Since there is only one person, it's not hard to show the difference between the number of left footprints and the number of right footprints is at most one. For a particular possible time order of a sequence of footprints, if there are $k$ backward steps, we can easily divide all footprints into at most $k + 1$ subsequences without backward steps. Then you might guess that another direction of the induction is also true.That is, we can combine any $k + 1$ subsequence without backward steps into a whole sequence contains at most $k$ backward steps. Your guess is correct ! Now we demostrate the process of combining those subsequences. We only concern the first step and the last step of a divided subsequence. There are four possible combinations, we denote them as $LL$/$LR$/$RL$/$RR$ subsequence separately(the first character is the type of the first step and the second character is the type of the second step). Suppose the number of four types of subseueqnce($LL$/$LR$/$RL$/$RR$) are $A$, $B$, $C$, $D$ separately. We have $abs(A - D) \le 1$. We can combine all $RR$, $LL$ subsequeces in turn into one subsequenceswith at most $A + D - 1$ backward steps(the result may be of any of the four subsquence types). Now we have at most one $LL$ or $RR$ type subsequence. Then we can combine all $RL$ subsequence into only one $RL$ subsequence with at most $A - 1$ backward steps easily. And so do $LR$ subsequences. Now we want to combine the final $RL$ and $LR$ subsequences together. We could pick the last footprint among two subsequences, exclude it from the original subsequcne and append it at the tail of another subsequence. The move will not increase the number of backward step and the types of the two subsequences would become $RR$ and $LL$ ! We can easily combine them into one $LR$ or $RL$ subsequence now. If there is still a $LL$ or $RR$ type subsequence reamained. We can easily combine them, too. So if we can divide all footprints into the least number of subsequences without backward steps. Then we have solved the problem. And this part can be done with greedy method. Now we provide one possible greedy method: Firstly, we translate this problem to a maximum matching problem on bipartite graph as following: Take "RLLRRL" as example: We split each footprint into two vertices which on is in left part and another is in right part. If two footprints is next to each other in resulted subsequnces, we will connect the left vertex of the former to right vertex of the latter in the corresponded matching. So the matching described in above left graph is subsequences: "RL-R--" and "--L-RL" and in above right graph is "RL-R-L" and "--L-R-". we can find that the number of subsequences is (number of footprints) - (value of matching). Due to the graphs produced by this problem is very special, we can solve this bipartite matching as following: Iterate each vertex in left part from top to bottom and find the uppermost vertex which is able to be matched in right part and connect them. If we process this algorithm in "RLLRRL", the resulted matching is the above right graph. Why the greedy method is correct? we can prove it by adjusting any maximum matching to our intended matching step by step. In each step, you can find the uppermost vertex the state of which is different to what we intend and change its state. I guess the mission of adjusting is not too hard for you to think out! Please solve it by yourself >_< By the way, I believe there are also many other greedy methods will work. If your greedy method is different to author's. Don't feel strange.
[ "constructive algorithms", "greedy" ]
2,700
#include<bits/stdc++.h> #define SZ(X) ((int)(X).size()) #define MP(X,Y) make_pair((X),(Y)) using namespace std; const int SIZE = 100010; char s[SIZE+5]; int nxt[SIZE],lat[SIZE]; bool pointed[SIZE]; int footprint_type(char c){return c=='R'?1:0;} vector<int>seq[2][2]; vector<int>an[SIZE]; int pn; void connect(int x,int y){ nxt[x]=y; lat[y]=x; } bool check(vector<pair<int,int> >&seq){ if(SZ(seq)<2)return 0; int st=seq.back().first,ed=seq.back().second,st2=seq[SZ(seq)-2].first,ed2=seq[SZ(seq)-2].second; if(s[ed]!=s[st2]){ connect(ed,st2); seq.pop_back(); seq.back()=MP(st,ed2); return 1; } if(s[ed2]!=s[st]){ connect(ed2,st); seq.pop_back(); seq.back()=MP(st2,ed); return 1; } if(s[st]!=s[ed]){ if(ed<ed2){ int z=lat[ed2]; connect(ed,ed2); connect(ed2,st2); nxt[z]=0; seq.pop_back(); seq.back()=MP(st,z); } else{ int z=lat[ed]; connect(ed2,ed); connect(ed,st); nxt[z]=0; seq.pop_back(); seq.back()=MP(st2,z); } return 1; } return 0; } int main(){ int m; scanf("%s",s+1); m=strlen(s+1); queue<int>qq[2]; for(int i=1;i<=m;i++){ int me=footprint_type(s[i]); if(SZ(qq[me^1])){ connect(qq[me^1].front(),i); pointed[i]=1; qq[me^1].pop(); } qq[me].push(i); } vector<pair<int,int> >seq; int cnt=-1; for(int i=1;i<=m;i++){ if(!pointed[i]){ cnt++; int ed=i; while(nxt[ed])ed=nxt[ed]; seq.push_back(MP(i,ed)); while(check(seq)); } } printf("%d\n",cnt); for(int i=0;i<SZ(seq);i++){ int now=seq[i].first; while(now){ if(i||now!=seq[i].first)printf(" "); printf("%d",now); now=nxt[now]; } } puts(""); return 0; }
578
F
Mirror Box
You are given a box full of mirrors. Box consists of grid of size $n × m$. Each cell of the grid contains a mirror put in the shape of '$\$' or '$ / $' ($45$ degree to the horizontal or vertical line). But mirrors in some cells have been destroyed. You want to put new mirrors into these grids so that the following two conditions are satisfied: - If you put a light ray horizontally/vertically into the middle of any unit segment that is side of some border cell, the light will go out from the neighboring unit segment to the segment you put the ray in. - each unit segment of the grid of the mirror box can be penetrated by at least one light ray horizontally/vertically put into the box according to the rules of the previous paragraph After you tried putting some mirrors, you find out that there are many ways of doing so. How many possible ways are there? The answer might be large, so please find the result modulo prime number $MOD$.
If we view the grid intersections alternatively colored by blue and red like this: Then we know that the two conditions in the description are equivalent to a spanning tree in either entire red intersections or entire blue dots. So we can consider a red spanning tree and blue spanning tree one at a time. We can use disjoint-sets to merge connected components. Each component should be a tree, otherwise some grid edges will be enclosed inside some mirrors. So for the contracted graph, we would like to know how many spanning trees are there. This can be done by Kirchhoff's theorem. Since there are at most 200 broken mirrors, the number of vertices in the contracted graph should be no more than 401. Hence a $O(|V|^{3})$ determinant calculation algorithm may be applied onto the matrix.
[ "matrices", "trees" ]
3,200
#include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include <cassert> #define SZ(x) ((int)(x).size()) #define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) using namespace std; typedef long long LL; char a[514][514]; int n, m; int ID[514][514]; int RID[20005]; int idt[20005]; int g[20005]; int FIND(int x) { return g[x]==x? x: (g[x]=FIND(g[x])); } void UNION(int x, int y) { x = FIND(x); y = FIND(y); g[x] = y; } int edge(int x, int y) { if (FIND(x) == FIND(y)) return 1; UNION(x, y); return 0; } LL P[2][514][514]; int MOD = 1e9+7; int nid=0, Pid[2]={}; void bridge(int x, int y) { x = FIND(x); y = FIND(y); if (x == y) return; P[idt[x]][RID[x]][RID[x]]++; P[idt[x]][RID[x]][RID[y]]--; P[idt[x]][RID[y]][RID[x]]--; P[idt[x]][RID[y]][RID[y]]++; } LL inv(LL x, LL y, LL p, LL q, LL r, LL s) { if (y==0) return (p%MOD+MOD)%MOD; return inv(y, x%y, r, s, p-r*(x/y), q-s*(x/y)); } LL det(LL F[514][514], int D) { LL ans = 1; for (int i = 0; i < D; i++) { int r = i; while(r < D && F[r][i] == 0) ++r; if (r >= D) return 0; if (r != i) ans = ans * (MOD-1) % MOD; for(int j=i;j<D;j++) swap(F[r][j], F[i][j]); ans = ans * F[i][i] % MOD; LL t = inv(F[i][i], MOD, 1, 0, 0, 1); for(int j=i;j<D;j++) F[i][j] = (F[i][j] * t) % MOD; for(int r=i+1;r<D;r++) if(F[r][i] != 0) { LL s = F[r][i]; for(int j=i;j<D;j++) { F[r][j] = (F[r][j] - s * F[i][j]) % MOD; if (F[r][j] < 0) F[r][j] += MOD; } } } return ans; } int main(void) { scanf("%d%d%d", &n, &m, &MOD); assert(1<=n && n<=100); assert(1<=m && m<=100); for(int i=0;i<n;i++) scanf("%s", a[i]); for(int i=0;i<n;i++) assert(strlen(a[i]) == m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) assert(a[i][j]=='/' || a[i][j]=='\\' || a[i][j]=='*'); for(int i=0;i<=n;i++) for(int j=0;j<=m;j++) { ID[i][j] = ++nid; g[nid] = nid; idt[nid] = (i%2)^(j%2); } int fail = 0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) { if (a[i][j] == '/') { fail |= edge(ID[i+1][j], ID[i][j+1]); } else if (a[i][j] == '\\') { fail |= edge(ID[i][j], ID[i+1][j+1]); } } if (fail) { puts("0"); return 0; } for(int i=0;i<=n;i++) for(int j=0;j<=m;j++) if(FIND(ID[i][j]) == ID[i][j]) { RID[ID[i][j]] = Pid[idt[ID[i][j]]]++; } int cnt = 0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if (a[i][j]=='*') { bridge(ID[i][j], ID[i+1][j+1]); bridge(ID[i+1][j], ID[i][j+1]); ++cnt; } } } assert(cnt <= 200); //fprintf(stderr, "* count = %d; D=%d; %d\n", cnt, Pid[0], Pid[1]); for(int z=0;z<2;z++) for(int i=0;i<Pid[z];i++) for(int j=0;j<Pid[z];j++) P[z][i][j] = (P[z][i][j] + MOD) % MOD; LL ans = det(P[0], Pid[0]-1) + det(P[1], Pid[1]-1); printf("%d\n", (int)(ans % MOD)); return 0; }
579
A
Raising Bacteria
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly $x$ bacteria in the box at some moment. What is the minimum number of bacteria you need to put into the box across those days?
Write down $x$ into its binary form. If the $i^{th}$ least significant bit is $1$ and $x$ contains $n$ bits, we put one bacteria into this box in the morning of $(n + 1 - i)^{th}$ day. Then at the noon of the $n^{th}$ day, the box will contain $x$ bacteria. So the answer is the number of ones in the binary form of $x$.
[ "bitmasks" ]
1,000
#include<cstdio> int main(){ int n,an=0; scanf("%d",&n); while(n){ if(n&1)an++; n>>=1; } printf("%d\n",an); return 0; }
579
B
Finding Team Member
There is a programing contest named SnakeUp, $2n$ people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are \textbf{distinct}. Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people $A$ and $B$ may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?
Sort all possible combinations from high strength to low strength. Then iterator all combinations. If two people in a combination still are not contained in any team. then we make these two people as a team.
[ "brute force", "implementation", "sortings" ]
1,300
#include<cstdio> int person[1000001][2],an[1001]; bool used[1001]; int main(){ int n; scanf("%d",&n); n*=2; for(int i=1;i<=n;i++) for(int j=1;j<i;j++){ int x; scanf("%d",&x); person[x][0]=i; person[x][1]=j; } used[0]=1; for(int i=1000000;i>0;i--){ if(!used[person[i][0]]&&!used[person[i][1]]){ used[person[i][0]]=1; used[person[i][1]]=1; an[person[i][0]]=person[i][1]; an[person[i][1]]=person[i][0]; } } for(int i=1;i<=n;i++){ if(i>1)printf(" "); printf("%d",an[i]); } puts(""); return 0; }
580
A
Kefa and First Steps
Kefa decided to make some money doing business on the Internet for exactly $n$ days. He knows that on the $i$-th day ($1 ≤ i ≤ n$) he makes $a_{i}$ money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence $a_{i}$. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order. Help Kefa cope with this task!
Note, that if the array has two intersecting continuous non-decreasing subsequence, they can be combined into one. Therefore, you can just pass the array from left to right. If the current subsequence can be continued using the $i$-th element, then we do it, otherwise we start a new one. The answer is the maximum subsequence of all the found ones. Asymptotics - $O(n)$.
[ "brute force", "dp", "implementation" ]
900
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=228228;\n\nlong long a[N],k,o,i,j,n,m;\n\nint main(){\n\tcin>>n;\n\tfor(i=0;i<n;i++)scanf(\"%d\",&a[i]);\n\tk=1;\n\tfor(i=1;i<n;i++)if(a[i]>=a[i-1])k++;else o=max(o,k),k=1;\n\to=max(o,k);\n\tcout<<o;\n}"
580
B
Kefa and Company
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has $n$ friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least $d$ units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
At first we sort all friends in money ascending order. Now the answer is some array subsegment. Next, we use the method of two pointers for finding the required subsegment. Asymptotics - $O(n$ $log$ $n)$.
[ "binary search", "sortings", "two pointers" ]
1,500
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=228228;\n\nchar e[21];\nvector<string> ot;\npair<int,pair<int,string> > a[N];\nlong long o,p[3]={-1,-1,-1};\nint i,j,l,r,n,m;\n\nint main(){\n\tcin>>n>>m;\n\tfor(i=0;i<n;++i){\n\t scanf(\"%d%d\",&a[i].F,&a[i].S.F);\n\t a[i].S.S=e;\n\t}\n\tsort(a,a+n);\n\tfor(l=0;l<n;o-=a[l].S.F,++l){\n\t\twhile(r<n && abs(a[l].F-a[r].F)<m)o+=a[r].S.F,++r;\n\t\tif(o>=p[0])p[0]=o,p[1]=l,p[2]=r;\n\t}\n\tfor(i=p[1];i<p[2];++i)ot.pb(a[i].S.S);\n\tcout<<p[0]<<\"\\n\";\n}"
580
C
Kefa and Park
Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of $n$ vertices with the root at vertex $1$. Vertex $1$ also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them. The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than $m$ \textbf{consecutive} vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.
Let's go down the tree from the root, supporting additional parameter $k$ - the number of vertices in a row met with cats. If $k$ exceeds $m$, then leave. Then the answer is the number of leaves, which we were able to reach. Asymptotics - $O(n)$.
[ "dfs and similar", "graphs", "trees" ]
1,500
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=228228;\n\nvector<long long> a[N];\nlong long c[N],o,x,y,i,j,n,m;\n\nvoid go(int v,int pr,int k){\n\tif(k>m)return;\n\tint ok=1;\n\tfor(int i=0;i<a[v].size();i++)if(a[v][i]!=pr)ok=0,go(a[v][i],v,k*c[a[v][i]]+c[a[v][i]]);\n\to+=ok;\n}\n\nint main(){\n\tcin>>n>>m;\n\tfor(i=0;i<n;i++)scanf(\"%d\",&c[i]);\n\tfor(i=1;i<n;i++)scanf(\"%d%d\",&x,&y),x--,y--,a[x].pb(y),a[y].pb(x);\n\tgo(0,-1,c[0]);\n\tcout<<o<<\"\\n\";\n}"
580
D
Kefa and Dishes
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were $n$ dishes. Kefa knows that he needs exactly $m$ dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the $i$-th dish gives him $a_{i}$ units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself $k$ rules of eating food of the following type — if he eats dish $x$ exactly before dish $y$ (there should be no other dishes between $x$ and $y$), then his satisfaction level raises by $c$. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!
A two-dimensional DP will be used to solve the problem. The first dimention is the mask of already taken dishes, and the second - the number of the last taken dish. We will go through all the zero bits of the current mask for the transitions. We will try to put the one in them, and then update the answer for a new mask. The answer will consist of the answer of the old mask, a dish value, which conforms to the added bit and the rule, that can be used. The final answer is the maximum of all the values of DP, where mask contains exactly $m$ ones. Asymptotics - $O(2^{n} * n^{2})$.
[ "bitmasks", "dp" ]
1,800
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\nconst long long A=100000000000000LL,N=1228228;\n\nlong long mask,i,j,n,m,k,a[N],b[N],x,y,z,c[21][21],o,ot,dp[N][21];\n\nlong long len(long long mask){\n\tlong long k=0;\n\tfor(i=0;i<n;i++)if(mask&b[i])k++;\n\treturn k;\n}\n\nint main(){\n\tcin>>n>>m>>k;\n\tfor(i=0;i<n;i++)scanf(\"%d\",&a[i]);\n\tb[0]=1;\n\tfor(i=1;i<=n;i++)b[i]=b[i-1]*2;\n\twhile(k--)scanf(\"%d%d%d\",&x,&y,&z),c[x-1][y-1]=z;\n\tfor(i=0;i<n;i++)dp[b[i]][i]=a[i];\n\tfor(mask=0;mask<b[n];mask++)for(i=0;i<n;i++)if(mask&b[i]){\n for(j=0;j<n;j++)if((mask&b[j])==0)dp[(mask|b[j])][j]=max(dp[(mask|b[j])][j],dp[mask][i]+c[i][j]+a[j]);\n\t}\n\tfor(mask=0;mask<b[n];mask++)if(len(mask)==m)for(i=0;i<n;i++)o=max(o,dp[mask][i]);\n\tcout<<o<<\"\\n\";\n}"
580
E
Kefa and Watch
One day Kefa the parrot was walking down the street as he was on the way home from the restaurant when he saw something glittering by the road. As he came nearer he understood that it was a watch. He decided to take it to the pawnbroker to earn some money. The pawnbroker said that each watch contains a serial number represented by a string of digits from $0$ to $9$, and the more quality checks this number passes, the higher is the value of the watch. The check is defined by three positive integers $l$, $r$ and $d$. The watches pass a check if a substring of the serial number from $l$ to $r$ has period $d$. Sometimes the pawnbroker gets distracted and Kefa changes in some substring of the serial number all digits to $c$ in order to increase profit from the watch. The seller has a lot of things to do to begin with and with Kefa messing about, he gave you a task: to write a program that determines the value of the watch. Let us remind you that number $x$ is called a period of string $s$ ($1 ≤ x ≤ |s|$), if $s_{i} = s_{i + x}$ for all $i$ from 1 to $|s| - x$.
At first, we calculate the hash for all line elements depending on their positions. That is, the hash of the number $k$, standing on the $i$-th position will be equal to $g_{i}$ * $k$, where $g$ is the base of the hash. We construct the segment tree of sums, which support a group modification, for all hashes. Thus, we can perform queries for modification in $O(log$ $n)$. It remains to deal with the queries of the second type. Let us assume, that we want to process the query 2 $l$ $r$ $d$. Obviously, the substring from $l$ to $r$ have a $d$-period, if a substring from $l + d$ to $r$ is equal to substring from $l$ to $r - d$. We can find out the sum of hashes at the subsegment with the help of the sums tree, so we can compare the two strings in $O(log$ $n)$. Asymptotics - $O(m$ $log$ $n)$.
[ "data structures", "hashing", "strings" ]
2,500
"#include<iostream>\n#include<math.h>\n#include<algorithm>\n#include<stdio.h>\n#include<map>\n#include<vector>\n#include<set>\n#include<iomanip>\n#define F first\n#define S second\n#define P system(\"PAUSE\");\n#define H return 0;\n#define pb push_back\nusing namespace std;\n\nconst long long A=100000000000000LL,N=228228;\nconst long long os[2]={11,13};\nconst long long MOD[2]={1000000007,1073676287};\n\nstring a;\nlong long t[2][2][N*4],st[2][N],dp[2][N],type,l,r,d,i,j,n,m[2];\n\nlong long Get(int k,int l,int r){\n l--,r--;\n if(!l)return dp[k][r];else return ((dp[k][r]-dp[k][l-1])%MOD[k]+MOD[k])%MOD[k];\n}\n\nvoid push(int k,int v,int l,int r){\n if(!t[k][1][v])return;\n int mid=(l+r)/2;\n t[k][0][v*2]=(t[k][1][v]*Get(k,l,mid))%MOD[k];\n t[k][0][v*2+1]=(t[k][1][v]*Get(k,mid+1,r))%MOD[k];\n t[k][1][v*2]=t[k][1][v*2+1]=t[k][1][v];\n t[k][1][v]=0;\n}\n\nvoid modi(int k,int v,int l,int r,int _l,int _r,long long g){\n if(_l>_r)return;\n if(l==_l && r==_r){\n t[k][0][v]=(g*Get(k,l,r))%MOD[k],t[k][1][v]=g;\n return;\n }\n int mid=(l+r)/2;\n push(k,v,l,r);\n modi(k,v*2,l,mid,_l,min(_r,mid),g),modi(k,v*2+1,mid+1,r,max(mid+1,_l),_r,g);\n t[k][0][v]=t[k][0][v*2]+t[k][0][v*2+1];\n}\n\nlong long get(int k,int v,int l,int r,int _l,int _r){\n if(_l>_r)return 0;\n if(l==_l && r==_r)return t[k][0][v];\n push(k,v,l,r);\n int mid=(l+r)/2;\n return (get(k,v*2,l,mid,_l,min(mid,_r))+get(k,v*2+1,mid+1,r,max(mid+1,_l),_r))%MOD[k];\n}\n\nint main(){\n cin>>n>>m[0]>>m[1];\n cin>>a;\n for(d=0;d<2;d++){\n st[d][0]=dp[d][0]=1;\n for(i=1;i<n;i++)st[d][i]=st[d][i-1]*os[d],st[d][i]%=MOD[d],dp[d][i]=dp[d][i-1]+st[d][i],dp[d][i]%=MOD[d];\n for(i=0;i<n;i++)modi(d,1,1,n,i+1,i+1,a[i]-'0'+1);\n }\n m[0]+=m[1];\n while(m[0]--){\n scanf(\"%d%d%d%d\",&type,&l,&r,&d);\n if(type==1){\n for(i=0;i<2;i++)modi(i,1,1,n,l,r,d+1);\n }else{\n if(l==r || (((get(0,1,1,n,l,r-d)*st[0][d])%MOD[0]==get(0,1,1,n,l+d,r))&&\n ((get(1,1,1,n,l,r-d)*st[1][d])%MOD[1]==get(1,1,1,n,l+d,r))))puts(\"YES\");else puts(\"NO\");\n }\n }\n}"
581
A
Vasya the Hipster
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had $a$ red socks and $b$ blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them. Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got. Can you help him?
The first number in answer (number of days which Vasya can dress fashionably) is $min(a, b)$ because every from this day he will dress one red sock and one blue sock. After this Vasya will have either only red socks or only blue socks or socks do not remain at all. Because of that the second number in answer is $max((a - min(a, b)) / 2, (b - min(a, b)) / 2)$. Asymptotic behavior of this solution - O(1).
[ "implementation", "math" ]
800
null
581
B
Luxurious Houses
The capital of Berland has $n$ multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row. Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same. The new architect is interested in $n$ questions, $i$-th of them is about the following: "how many floors should be added to the $i$-th house to make it luxurious?" (for all $i$ from $1$ to $n$, inclusive). You need to help him cope with this task. Note that all these questions are independent from each other — the answer to the question for house $i$ does not affect other answers (i.e., the floors to the houses are not actually added).
This problem can be solved in the following way. Let's iterate on given array from the right to the left and will store in variable $maxH$ the maximal height if house which we have already considered.Then the answer to house number $i$ is number $max(0, maxH + 1 - h_{i})$, where $h_{i}$ number of floors in house number $i$. Asymptotic behavior of this solution - O($n$), where $n$ - number of houses.
[ "implementation", "math" ]
1,100
null
581
C
Developing Skills
Petya loves computer games. Finally a game that he's been waiting for so long came out! The main character of this game has $n$ different skills, each of which is characterized by an integer $a_{i}$ from 0 to 100. The higher the number $a_{i}$ is, the higher is the $i$-th skill of the character. The total rating of the character is calculated as the sum of the values ​​of $\frac{a_{i}}{10}\Big\}$ for all $i$ from 1 to $n$. The expression $⌊ x⌋$ denotes the result of rounding the number $x$ down to the nearest integer. At the beginning of the game Petya got $k$ improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if $a_{4} = 46$, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused. Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.
This problem can be solved in many ways. Let's consider the most intuitive way that fits in the given time. In the beginning we need to sort given array in the following way - from two numbers to the left should be the number to which must be added fewer units of improvements to make it a multiple of 10. You must add at least one unit of energy to every of this numbers. For example, if given array is ${45, 30, 87, 26}$ after the sort the array must be equal to ${87, 26, 45, 30}$. Now we iterate on the sorted array for $i$ from 1 to $n$. Let's $cur = 10 - (a_{i}mod10)$. If $cur \le k$ assign $a_{i} = a_{i} + cur$ and from $k$ subtract $cur$ else if $cur > k$ break from cycle. The next step is to iterate on array in the same way. Now we need only to calculate answer $ans$ - we iterate on array for $i$ from 1 to $n$ and assign $ans = ans + (a_{i} / 10)$. Asymptotic behavior of this solution - O($n * log(n)$) where $n$ is the number of hero skills.
[ "implementation", "math", "sortings" ]
1,400
null
581
D
Three Logos
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard. Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
This problem can be solved in many ways, let's consider one of them. The first step is to calculate sum of squares $s$ of given rectangles. Then the side of a answer square is $sqrt(s)$. If $sqrt(s)$ is not integer print -1. Else we need to make the following. We brute the order in which we will add given rectangles in the answer square (we can do it with help of $next_permutation())$ and for every order we brute will we rotate current rectangle on 90 degrees or not (we can do it with help of bit masks). In the beginning on every iteration the answer square $c$ in which we add the rectangles is empty. For every rectangle, which we add to the answer square we make the following - we need to find the uppermost and leftmost empty cell $free$ in answer square $c$ (recall that we also brute will we rotate the current rectangle on 90 degrees or not). Now we try to impose current rectangle in the answer square $c$ and the top left corner must coinside with the cell $free$. If current rectangle fully placed in the answer square $c$ and does not intersect with the some rectangle which has already been added, we need to fill by the required letter appropriate cells in the answer square $c$. If no one of the conditions did not disrupted after we added all three rectangles and all answer square $c$ is fully filled by letters we found answer and we neeed only to print the answer square $c$. Else if we did not find answer after all iterations on the rectangles - print -1. For random number of the rectangles $k$ asymptotic behavior - O($k! * 2^{k} * s$) where $s$ - the sum of squares of the given rectangles. Also this problem with 3 rectangles can be solved with the analysis of the cases with asymptotic O($s$) where $s$ - the sum of squares of given rectangles.
[ "bitmasks", "brute force", "constructive algorithms", "geometry", "implementation", "math" ]
1,700
null
581
E
Kojiro and Furrari
Motorist Kojiro spent $10$ years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her. Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point $f$ of a coordinate line, and Johanna is at point $e$. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers $t_{i}$ and $x_{i}$ — the number of the gas type and its position. One liter of fuel is enough to drive for exactly $1$ km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly $s$ liters of fuel (regardless of the type of fuel). At the moment of departure from point $f$ Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than $s$ liters. Note that the tank \textbf{can} simultaneously have different types of fuel. The car can moves both left and right. To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from $f$ to $e$, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95. Write a program that can for the $m$ possible positions of the start $f_{i}$ minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.
Let's $f$ - the position of start, and $e$ - the position of finish. For convenience of implementation we add the gas-station in point $e$ with type equals to $3$. Note: there is never a sense go to the left of the starting point because we already stand with a full tank of the besr petrol. It is correct for every gas-station in which we can appear (if in optimal answer we must go to the left in some gas-station $pv$, why not throw out all the way from $pv$ to current gas-station $v$ and back and after that the answer will be better). Now let's say about algorithm when we are in some gas-station $v$. The first case: on distance no more than $s$ there is the gas-station with quality of gasoline not worse, than in the current gas-station. Now we fix nearest from them $nv$ (nearest to the right because go to the left as we understand makes no sense). In that case we refuel in such a way to can reach $nv$ and go to $nv$. The second case: from the current gas-station we can reach only gas-station with the worst quality (the type of the current gas-station can be 2 or 3). If we are in the gas-station of type 2 we need to refuel on maximum possiblevalue and go in the last achievable gas-station. If we are in the gas-station with type 3, we need to go in the farthest gas-station with type $2$, but if there is not such gas-station we need to go to the farthest gas-station with type $1$. This reasoning are correct because we first need to minimze the count of fuel with type $1$, and the second to minimize the count of fuel with type $2$. This basic reasoning necessary to solve the problem. The next step - calc dynamic on all suffixes $i$ of gas-stations - the answer to the problem if we start from the gas-station $i$ with empty tank. We need to make updates, considering the above cases. For update the dynamic in $v$ we need to take the value of dynamic in $nv$ and make update in addiction of the case. If the case is equals to $1$, we need to add to appropriate value the distance $d$ from $v$ to $nv$. If this case is equals to $2$ and we are in the gas-station with type equals to $2$ we need to add $s$ to the second value of answer, and from the first value we need to substract $s-d$. If it is the case number $2$ and we are in the gas-station with type equals to $3$, we need to substract from the value, which determined by the type of the gas-station $nv$, $s-d$. Now to answer on specific query of the starting position we nned to find the first gas-station which is to the right of the startiong position, make one update and take the value of dynamic, which already calculated, and recalculate this value in accordance with the above. Asymptotic behavior - O(n logn) or O(n) in case how we find position in the list of gas-stations (the first in case of binary search, the second in case of two pointers). To this solution we need O(n) memory.
[ "dp", "greedy" ]
2,800
null
581
F
Zublicanes and Mumocrates
It's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on $n$ main squares of the capital of Berland. Each of the $n$ squares certainly can have demonstrations of only one party, otherwise it could lead to riots. On the other hand, both parties have applied to host a huge number of demonstrations, so that on all squares demonstrations must be held. Now the capital management will distribute the area between the two parties. Some pairs of squares are connected by $(n - 1)$ bidirectional roads such that between any pair of squares there is a unique way to get from one square to another. Some squares are on the outskirts of the capital meaning that they are connected by a road with only one other square, such squares are called dead end squares. The mayor of the capital instructed to distribute all the squares between the parties so that the dead end squares had the same number of demonstrations of the first and the second party. It is guaranteed that the number of dead end squares of the city is even. To prevent possible conflicts between the zublicanes and the mumocrates it was decided to minimize the number of roads connecting the squares with the distinct parties. You, as a developer of the department of distributing squares, should determine this smallest number.
Let the number of leavs in tree (vertices with degree 1) is equal to $c$. It said in statement that $c$ is even. If in given graph only 2 vertices the answer is equal to $1$. Else we have vertex in graph which do not a leaf - we hang the three on this vertex. Now we need to count 2 dynamics. The first $z1[v][cnt][col]$ - the least amount of colored edges in the subtree rooted at the vertex $v$, if vertex $v$ already painted in color $col$ ($col$ equals to $0$ or to $1$), and among the top of the leaves of the subtree $v$ must be exactly $cnt$ vertices with color $0$. If we are in the leaf, it is easy to count this value. If we are not in the leaf - we count value with help of dynamic $z1[v][cnt][col]: = z2[s][cnt][col]$, where $s$ - the first child int the adjacency list of vertex $v$. We need the second dynamic $z2[s][cnt][col]$ to spread $cnt$ leaves with color $0$ among subtrees of childs of vertex $v$. To calc $z2[s][cnt][col]$ we brute the color of child $s$ - $ncol$ and the number of childs $i$ with color $0$, which will be locate in subtree of vertex $s$ and calc the value in the following way - $z2[s][cnt][col] = min(z2[s][cnt][col], z2[ns][cnt-a][col] + z1[s][a][ncol] + (ncol! = col))$, where $ns$ - the next child of vertex $v$ after the child $s$. Note, that it is senselessly to take $a$ more than the number of leaves in the subtree $s$ and to take more than the number of vertices in subtree - $size_{s}$ (because in that case it will not be enough leaves for painting). The upper bound of asymptotic for such dynamics $O(n^{3})$. We show that in fact it works with asymptotic $O(n^{2})$. Let's count the number of updates: $\begin{array}{l}{{\sum_{v=1}^{n}\sum_{i=1}^{s z(g[v])}(\sum_{j=1}^{i-1}s i z e_{g_{v,j}}.s i z e_{g_{v,i}})=\sum_{v=1}^{n}\sum_{i=1}^{s z(g[v])}\sum_{j=1}^{i-1}s i z e_{g_{v,i}}.s i z e_{g_{v,j}}}\end{array}$. Note, that every pair of vertices $(x, y)$ appears in the last sum $(x, y)$ exactly once when $v = lca(x, y)$. So we have no more than $O(n^{2})$ updates. Asymptotic behavior of this solution: $O(n^{2})$.
[ "dp", "trees", "two pointers" ]
2,400
null
582
A
GCD Table
The GCD table $G$ of size $n × n$ for an array of positive integers $a$ of length $n$ is defined by formula \begin{center} $g_{i j}=\operatorname*{gcd}(a_{i},a_{j}).$ \end{center} Let us remind you that the greatest common divisor (GCD) of two positive integers $x$ and $y$ is the greatest integer that is divisor of both $x$ and $y$, it is denoted as $\operatorname*{gcd}(x,y)$. For example, for array $a = {4, 3, 6, 2}$ of length 4 the GCD table will look as follows: Given all the numbers of the GCD table $G$, restore array $a$.
Let the answer be $a_{1} \le a_{2} \le ... \le a_{n}$. We will use the fact that $gcd(a_{i}, a_{j}) \le a_{min(i, j)}$. It is true that $gcd(a_{n}, a_{n}) = a_{n} \ge a_{i} \ge gcd(a_{i}, a_{j})$ for every $1 \le i, j \le n$. That means that $a_{n}$ is equal to maximum element in the table. Let set $a_{n}$ to maximal element in the table and delete it from table elements set. We've deleted $gcd(a_{n}, a_{n})$, so the set now contains all $gcd(a_{i}, a_{j})$, for every $1 \le i, j \le n$ and $1 \le min(i, j) \le n - 1$. By the last two inequalities $gcd(a_{i}, a_{j}) \le a_{min(i, j)} \le a_{n - 1} = gcd(a_{n - 1}, a_{n - 1})$. As soon as set contains $gcd(a_{n - 1}, a_{n - 1})$, the maximum element in current element set is equal to $a_{n - 1}$. As far as we already know $a_{n}$, let's delete the $gcd(a_{n - 1}, a_{n - 1})$, $gcd(a_{n - 1}, a_{n})$, $gcd(a_{n}, a_{n - 1})$ from the element set. Now set contains all the $gcd(a_{i}, a_{j})$, for every $1 \le i, j \le n$ and $1 \le min(i, j) \le n - 2$. We're repeating that operation for every $k$ from $n - 2$ to $1$, setting $a_{k}$ to maximum element in the set and deleting the $gcd(a_{k}, a_{k})$, $gcd(a_{i}, a_{k})$, $gcd(a_{k}, a_{i})$ for every $k < i \le n$ from the set. One could prove correctness of this algorithm by mathematical induction. For performing deleting and getting maximum element operations one could use multiset or map structure, so solution has complexity $O(n^{2}\log{n})$.
[ "constructive algorithms", "greedy", "number theory" ]
1,700
#include <cstdio> #include <map> #include <cassert> #define forn(i, n) for (int i = 0; i < int(n); ++i) using namespace std; const int N = 1000; map <int, int> cnt; int ans[N]; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int main() { int n; scanf("%d", &n); forn(i, n * n) { int a; scanf("%d", &a); cnt[-a]++; } int pos = n - 1; for (map <int, int> :: iterator it = cnt.begin(); it != cnt.end(); ++it) { int x = -it->first; while (it->second) { ans[pos] = x; --it->second; for (int i = pos + 1; i < n; ++i) cnt[-gcd(ans[pos], ans[i])] -= 2; pos--; } } forn(i, n) printf("%d ", ans[i]); return 0; }
582
B
Once Again...
You are given an array of positive integers $a_{1}, a_{2}, ..., a_{n × T}$ of length $n × T$. We know that for any $i > n$ it is true that $a_{i} = a_{i - n}$. Find the length of the longest non-decreasing sequence of the given array.
One could calculate matrix sized $n \times n$ $mt[i][j]$ - the length of the longest non-decreasing subsequence in array $a_{1}, a_{2}, ..., a_{n}$, starting at element, greater-or-equal to $a_{i}$ and ending strictly in $a_{j}$ element with $j$-th index. One could prove that if we have two matrices sized $n \times n$ $A[i][j]$ (the answer for $a_{1}, a_{2}, ..., a_{pn}$ starting at element, greater-or-equal to $a_{i}$ and ending strictly in $a_{j}$ element with $j$-th index inside last block ($a_{(p - 1)n + 1}, ..., a_{pn}$) and $B[i][j]$ (the answer for $a_{1}, a_{2}, ..., a_{qn}$ ), then the multiplication of this matrices in a way $C[i][j]={\underset{k=1}{\operatorname*{max}}}\left(A[i][k]+B[k][j]\right)$ will give the same matrix but for length $p + q$. As soon as such multiplication is associative, next we will use fast matrix exponentiation algorithm to calculate $M[i][j]$ (the answer for $a_{1}, a_{2}, ..., a_{nT}$) - matrix $mt[i][j]$ raised in power $T$. The answer is the maximum in matrix $M$. Such solution has complexity $O(n^{3}\log T)$. Jury's solution (with matrices): 13390660 There's an alternative solution. As soon as $a_{1}, a_{2}, ..., a_{nT}$ contains maximum $n$ distinct elements, it's any non-decreasing subsequence has a maximum of $n - 1$ increasing consequtive element pairs. Using that fact, one could calculate standard longest non-decreasing subsequence dynamic programming on first $n$ array blocks ($a_{1}, ..., a_{n^{2}}$) and longest non-decreasing subsequence DP on the last $n$ array blocks ($a_{nT - n + 1}, ..., a_{nT}$). All other $T - 2n$ blocks between them will make subsegment of consequtive equal elements in longest non-decreasing subsequence. So, for fixed $a_{i}$, in which longest non-decreasing subsequence of length $p$ on first $n$ blocks array ends, and for fixed $a_{j} \ge a_{i}$, in which longest non-decreasing subsequence of length $s$ on last $n$ blocks array starts, we must update the answer with $p + (T - 2n)count(a_{i}) + s$, where $count(x)$ is the number of occurences of $x$ in $a_{1}, ..., a_{n}$ array. This gives us $O(n^{2}\log{n})$ solution.
[ "constructive algorithms", "dp", "matrices" ]
1,900
#include <bits/stdc++.h> using namespace std; const int N = 100 + 5; int n, T, a[N]; vector <int> build(int t) { vector <int> res(n * t); for (int i = 0; i < n * t; ++i) res[i] = (i < n) ? a[i] : res[i - n]; return res; } vector <int> calc_lis(vector <int> a) { int n = a.size(); vector <int> res(n), dp(n + 1, 500); dp[0] = -1; for (int i = 0; i < n; ++i) { res[i] = upper_bound(dp.begin(), dp.end(), a[i]) - dp.begin(); dp[ res[i] ] = a[i]; } return res; } int main() { cin >> n >> T; for (int i = 0; i < n; ++i) cin >> a[i]; int res = 0; if (T <= 2 * n) { vector <int> A = build(T); A = calc_lis(A); for (int i = 0; i < n * T; ++i) res = max(res, A[i]); } else { vector <int> A = build(n); vector <int> inc = calc_lis(A); for (int i = 0; i < n * n; ++i) A[i] = 301 - A[i]; reverse(A.begin(), A.end()); vector <int> dec = calc_lis(A); reverse(dec.begin(), dec.end()); for (int i = 0; i < n; ++i) { int cnt = 0; for (int j = 0; j < n; ++j) if (a[i] == a[j]) cnt++; for (int j = 0; j < n; ++j) { if (a[j] < a[i]) continue; res = max(res, inc[(n - 1) * n + i] + cnt * (T - 2 * n) + dec[j]); } } } cout << res << endl; return 0; }
582
C
Superior Periodic Subarrays
You are given an infinite periodic array $a_{0}, a_{1}, ..., a_{n - 1}, ...$ with the period of length $n$. Formally, $a_{i}=a_{i}{\bmod{n}}$. A periodic subarray $(l, s)$ ($0 ≤ l < n$, $1 ≤ s < n$) of array $a$ is an infinite periodic array with a period of length $s$ that is a subsegment of array $a$, starting with position $l$. A periodic subarray $(l, s)$ is superior, if when attaching it to the array $a$, starting from index $l$, any element of the subarray is larger than or equal to the corresponding element of array $a$. An example of attaching is given on the figure (top — infinite array $a$, bottom — its periodic subarray $(l, s)$): Find the number of distinct pairs $(l, s)$, corresponding to the superior periodic arrays.
Let's fix $s$ for every $(l, s)$ pair. One could easily prove, that if subarray contains $a_{i}$ element, than $a_{i}$ must be greater-or-equal than $a_{j}$ for every $j$ such that $i\equiv j\mathrm{\mod\}g c d(n,s)$. Let's use this idea and fix $g = gcd(n, s)$ (it must be a divisor of $n$). To check if $a_{i}$ can be in subarray with such constraints, let's for every $0 \le r < g$ calculate $p n l l\imath_{r}\implies\operatorname*{max}_{i\equiv r\mod{g}}$. It's true that every good subarray must consist of and only of $a_{i}=r n n_{i}\;\mathrm{\,mod\,}g$. For finding all such subarrays we will use two pointers approach and for every good $a_{i}$, such that $\ U(i{-}1)\mod n$ is not good we will find $a_{j}$ such that $\qquad d_{i},\ Q_{(i+1)}\quad\mathrm{mod}\ n\,,\ \cdot\cdot\cdot\cdot\cdot\alpha_{j}$ are good and $U(j+1)\mod n)$ is not good. Let $\begin{array}{r l}{{a_{i},\,Q_{(i+1)}}}&{{\operatorname*{mod}\,n,\,\cdot\,\cdot\,\cdot\,\cdot\,\cdot\,Q_{j}}}\end{array}$ has $k$ elements $i+k-1\equiv j\mod n)$. Any it's subarray is superior, so it gives us arrays of length $1, 2, ..., k$ with count $k, k - 1, ..., 1$. As soon as sum of all $k$ is not greater than $n$, we could just increase counts straightforward. There's a case when all $a_{i}$ are good, in which we must do another increases. Next we must add to the answer only counts of length $x$, such that $gcd(x, n) = g$. Solution described above has complexity $O(d(n)n)$, where $d(n)$ is the number of divisors of $n$.
[ "number theory" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 1000 * 1000 + 5; int a[N], n, c[N], gg[N]; bool u[N]; inline int inc(int v) { return (v + 1 == n) ? 0 : (v + 1); } inline int gcd(int a, int b) { return b ? gcd(b, a % b) : a; } int main() { assert(scanf("%d", &n) == 1); for (int i = 0; i < n; ++i) assert(scanf("%d", &a[i]) == 1); for (int i = 1; i <= n; ++i) gg[i] = gcd(i, n); long long res = 0; for (int g = 1; g < n; ++g) { if (n % g != 0) continue; for (int i = 0; i < n; ++i) u[i] = false, c[i] = 0; for (int i = 0; i < g; ++i) { int mx = -1; for (int j = i; j < n; j += g) mx = max(mx, a[j]); for (int j = i; j < n; j += g) if (a[j] == mx) u[j] = true; } bool any = false; for (int l = 0; l < n;) { int r = inc(l); if (u[l]) { l++; continue; } any = true; int len = 0; while (u[r]) len++, r = inc(r); for (int i = 1; i <= len; ++i) c[i] += len - i + 1; if (r <= l) break; l = r; } if (!any) for (int i = 1; i <= n; ++i) c[i] += n; for (int i = 1; i <= n; ++i) if (gg[i] == g) res += c[i]; } cout << res << endl; return 0; }
582
D
Number of Binominal Coefficients
For a given prime integer $p$ and integers $α, A$ calculate the number of pairs of integers $(n, k)$, such that $0 ≤ k ≤ n ≤ A$ and $\textstyle{\binom{n}{k}}$ is divisible by $p^{α}$. As the answer can be rather large, print the remainder of the answer moduly $10^{9} + 7$. Let us remind you that $\textstyle{\binom{n}{k}}$ is the number of ways $k$ objects can be chosen from the set of $n$ objects.
It is a common fact that for a prime $p$ and integer $n$ maximum $ \alpha $, such that $p^{ \alpha }|n!$ is calculated as $\alpha=\left.\left\{{\frac{n}{p}}\right\}+\left[{\frac{n}{p^{2}}}\right\}+\cdot\cdot\cdot+\left.\right.\left\{{\frac{n}{p^{w}}}\right\}$, where $p^{w} \le n < p^{w + 1}$. As soon as ${\binom{n}{k}}={\frac{n!}{k!(n-k)!}}$, the maximum $ \alpha $ for $\textstyle{\binom{n}{k}}$ is calculated as $\alpha={\bigg(}|{\frac{n}{p}}|-\biggl(|{\frac{k}{p}}|+|{\frac{n-k}{p}}|{\bigg)}{\bigg)}+{\bigg(}[{\frac{n}{p^{2}}}]-{\bigg(}[{\frac{k}{p^{2}}}]+[{\frac{n-k}{p^{2}}}]{\bigg)}{\bigg)}+\ldots+{\bigg(}[{\frac{k}{p^{2}}}]+\left({\frac{n-k}{p^{4}}}\right){\bigg)}$. One could see, that if we consider numbers $n$, $k$ and $n - k$ in $p$-th based numeric system, rounded-down division by $p^{x}$ means dropping last $x$ digits of its $p$-th based representation. As soon as $k + (n - k) = n$, every $i$-th summand in $ \alpha $ corresponds to carry in adding $k$ to $n - k$ in $p$-th numeric system from $i - 1$-th to $i$-th digit position and is to be 0 or 1. First, let convert $A$ given in statement from $10$ to $p$-th numeric system. In case, if $ \alpha $ is greater than number of digits in $A$ in $p$-th numeric system, the answer is $0$. Next we will calculate dynamic programming on $A$ $p$-th based representation. $dp[i][x][e][r]$ - the answer for prefix of length $i$ possible equal to prefix of $A$ representation (indicator $e$), $x$-th power of $p$ was already calculated, and there must be carry equal to $r$ from current to previous position. One could calculate it by bruteforcing all of $p^{2}$ variants of placing $i$-th digits in $n$ and $k$ according to $r$ and $e$ and $i$-th digit of $A$, and make a translation to next state. It can be avoided by noticing that the number of variants of placing digits is always a sum of arithmetic progression and can be calculated in $O(1)$. It's highly recommended to examine jury's solution with complexity $O(|A|^{2} + |A|min(|A|, \alpha ))$.
[ "dp", "math", "number theory" ]
3,300
#include <bits/stdc++.h> using namespace std; const int N = 3400; const int MOD = int(1e9) + 7; inline int add(int a, int b) { return (a + b >= MOD) ? (a + b - MOD) : (a + b); } inline int sub(int a, int b) { return (a - b < 0) ? (a - b + MOD) : (a - b); } inline void inc(int &a, int b) { a = add(a, b); } inline int mul(int a, int b) { return (a * 1ll * b) % MOD; } char s[N]; vector <int> a; int p, alpha; int dp[N][N][2][2]; int div(const vector <int> &a, const int b, vector <int> &c) { c.clear(); long long r = 0; for (int i = 0; i < a.size(); ++i) { r = r * 10ll + a[i]; if (c.size() || r >= b) c.push_back(r / b); r %= b; } return r; } inline int calc_w(int c, int rm, int nrm) { if (rm) return p - calc_w(c, !rm, nrm); return c + 1 - nrm; } inline int calc_W(int c, int rm, int nrm) { if (rm) return sub(mul(p, c + 1), calc_W(c, !rm, nrm)); if (c & 1) return sub(mul(c + 2, (c + 1) >> 1), nrm * (c + 1)); return sub(mul(c + 1, (c + 2) >> 1), nrm * (c + 1)); } int main() { assert(scanf("%d %d", &p, &alpha) == 2); assert(scanf("%s", s) == 1); a.resize(strlen(s)); for (int i = 0; i < a.size(); ++i) a[i] = s[i] - '0'; vector <int> b, c; while (a.size()) { c.push_back(div(a, p, b)); a = b; } reverse(c.begin(), c.end()); if (alpha > c.size()) { puts("0"); return 0; } dp[0][0][1][0] = 1; int n = c.size(); for (int i = 0; i < n; ++i) for (int pw = 0; pw <= alpha; ++pw) for (int eq = 0; eq < 2; ++eq) for (int rm = 0; rm < 2; ++rm) { int &cur = dp[i][pw][eq][rm]; if (cur == 0) continue; for (int nrm = 0; nrm < 2; ++nrm) { int npw = min(pw + nrm, alpha); if (!eq) inc(dp[i + 1][npw][eq][nrm], mul(calc_W(p - 1, rm, nrm), cur)); else { if (c[i] != 0) inc(dp[i + 1][npw][!eq][nrm], mul(calc_W(c[i] - 1, rm, nrm), cur)); inc(dp[i + 1][npw][eq][nrm], mul(calc_w(c[i], rm, nrm), cur)); } } } int res = 0; for (int eq = 0; eq < 2; ++eq) inc(res, dp[n][alpha][eq][0]); printf("%d\n", res); return 0; }
582
E
Boolean Function
In this problem we consider Boolean functions of four variables $A, B, C, D$. Variables $A, B, C$ and $D$ are logical and can take values 0 or 1. We will define a function using the following grammar: <expression> ::= <variable> | (<expression>) <operator> (<expression>) <variable> ::= 'A' | 'B' | 'C' | 'D' | 'a' | 'b' | 'c' | 'd' <operator> ::= '&' | '|' Here large letters $A, B, C, D$ represent variables, and small letters represent their negations. For example, if $A = 1$, then character 'A' corresponds to value 1, and value character 'a' corresponds to value 0. Here character '&' corresponds to the operation of logical AND, character '|' corresponds to the operation of logical OR. You are given expression $s$, defining function $f$, where some operations and variables are missing. Also you know the values of the function $f(A, B, C, D)$ for some $n$ distinct sets of variable values. Count the number of ways to restore the elements that are missing in the expression so that the resulting expression corresponded to the given information about function $f$ in the given variable sets. As the value of the result can be rather large, print its remainder modulo $10^{9} + 7$.
One could prove that the number of binary functions on 4 variables is equal to $2^{24}$, and can be coded by storing a $2^{4}$-bit binary mask, in which every bit is storing function value for corresponding variable set. It is true, that if $mask_{f}$ and $mask_{g}$ are correspond to functions $f(A, B, C, D)$ and $g(A, B, C, D)$, then function $(f&g)(A, B, C, D)$ corresponds to $mask_{f}&mask_{g}$ bitmask. Now, we could parse expression given input into binary tree. I should notice that the number of non-list nodes of such tree is about $\frac{|s s|}{\mathrm{G}}$. Now, let's calculate dynamic programming on every vertex $v$ - $dp[v][mask]$ is the number of ways to place symbols in expression in the way that subtree of vertex $v$ will correspond to function representing by $mask$. For list nodes such dynamic is calculated pretty straightforward by considering all possible $mask$ values and matching it with the variable. One could easily recalculate it for one node using calculated answers for left and right subtree in $4^{16}$ operations: $dp[v][lmask|rmask] + = dp[l][lmask] * dp[r][rmask]$. But all the task is how to make it faster. One could calculate $s[mask]$, where $s[mask]$ is equal to sum of all its submasks (the masks containing 1-bits only in positions where $mask$ contains 1-bits) in $2^{4} \cdot 2^{24}$ operations using following code: for (int mask = 0; mask < (1 << 16); ++mask) s[mask] = dp[x][mask]; for (int i = 0; i < 16; ++i) for (int mask = 0; mask < (1 << 16); ++mask) if (!(mask & (1 << i))) s[mask ^ (1 << i)] += s[mask];Let's calculate $sl[mask]$ and $sr[mask]$ for $dp[l][mask]$ and $dp[r][mask]$ respectively. If we will find $s[mask] = sl[mask] * sr[mask]$, $s[mask]$ will contain multiplications of values of pairs of masks from left and right $dp$'s, which are submasks of $mask$. As soon as we need pairs, which in bitwise OR will give us exactly $mask$, we should exclude pairs, which in bitwise OR gives a submask of $mask$, not equal to $mask$. This gives us exclusion-inclusion principle idea. The formula of this will be $s[m a s k]=\sum_{s m a s k}(-1)^{p}s l[s m a s k]\cdot s r[s m a s k]\cdot s r[s m a s k]$, where $p$ is the parity of number of bits in $mask^submask$. Such sum could be calculated with approach above, but subtracting instead of adding for (int mask = 0; mask < (1 << 16); ++mask) s[mask] = sl[mask] * sr[mask]; for (int i = 0; i < 16; ++i) for (int mask = 0; mask < (1 << 16); ++mask) if (!(mask & (1 << i))) s[mask ^ (1 << i)] -= s[mask];In such way we will recalculate dynamic for one vertex in about $3 \cdot 2^{4} \cdot 2^{16}$ operations.
[ "bitmasks", "dp", "expression parsing" ]
3,000
#include <bits/stdc++.h> using namespace std; const int MOD = int(1e9) + 7; inline int add(int a, int b) { return (a + b >= MOD) ? (a + b - MOD) : (a + b); } inline void inc(int &a, int b) { a = add(a, b); } inline int sub(int a, int b) { return (a - b < 0) ? (a - b + MOD) : (a - b); } inline void dec(int &a, int b) { a = sub(a, b); } inline int mul(int a, int b) { return (a * 1ll * b) % MOD; } const int N = 200 + 5; const int V = 4; const int S = (1 << V); const int M = (1 << S); char s[N * 6]; int n, d[N][M]; const string vars = "ABCDabcd"; const string ops = "&|"; int maskone(int v) { int mask = 0; for (int i = 0; i < S; ++i) if ((i >> v) & 1) mask |= (1 << i); return mask; } #define negate ____negate void negate(int *a) { reverse(a, a + M); } void copy(const int *a, int *b) { for (int i = 0; i < M; ++i) b[i] = a[i]; } void add(const int *a, int *b) { for (int i = 0; i < M; ++i) inc(b[i], a[i]); } void sumsub(const int *a, int *b, int d) { copy(a, b); for (int i = 0; i < S; ++i) for (int mask = 0; mask < M; ++mask) if (!(mask & (1 << i))) { if (d == +1) inc(b[mask ^ (1 << i)], b[mask]); else if (d == -1) dec(b[mask ^ (1 << i)], b[mask]); else throw; } } int t1[M], t2[M], tops[2][M]; void door(const int *l, const int *r, int *v) { sumsub(l, t1, +1); sumsub(r, t2, + 1); for (int i = 0; i < M; ++i) t1[i] = mul(t1[i], t2[i]); sumsub(t1, v, -1); } int parse(int &pos) { if (s[pos] != '(') { int v = vars.find(s[pos++]); if (v == -1) { for (int i = 0; i < V; ++i) { d[n][maskone(i)] = 1; d[n][(M - 1) ^ maskone(i)] = 1; } } else { if (v < V) d[n][maskone(v)] = 1; else d[n][(M - 1) ^ maskone(v - V)] = 1; } return n++; } int me = n++; int l = parse(++pos); assert(s[pos++] == ')'); int v = ops.find(s[pos++]); int r = parse(++pos); assert(s[pos++] == ')'); door(d[l], d[r], tops[1]); // tops[1] = (l | r) negate(d[l]); // d[l] = ~l negate(d[r]); // d[r] = ~r door(d[l], d[r], tops[0]); // tops[0] = (~l | ~r) negate(tops[0]); // tops[0] = ~(~l | ~r) = (l & r) negate(d[r]); // d[r] = r negate(d[l]); // d[l] = l if (v == -1) for (int i = 0; i < ops.size(); ++i) add(tops[i], d[me]); else add(tops[v], d[me]); return me; } int req[1 << V]; int main() { scanf("%s", s); int pos = 0; int root = parse(pos); scanf("%d", &n); for (int i = 0; i < S; ++i) req[i] = -1; for (int i = 0; i < n; ++i) { int mask = 0; for (int j = 0; j < V; ++j) { int a; scanf("%d", &a); mask |= (a << j); } scanf("%d", &req[mask]); } int res = 0; for (int i = 0; i < M; ++i) { bool good = true; for (int j = 0; j < S; ++j) good &= (req[j] == -1 || req[j] == ((i >> j) & 1)); if (good) inc(res, d[root][i]); } printf("%d\n", res); return 0; }
583
A
Asphalting Roads
City X consists of $n$ vertical and $n$ horizontal infinite roads, forming $n × n$ intersections. Roads (both vertical and horizontal) are numbered from $1$ to $n$, and the intersections are indicated by the numbers of the roads that form them. Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted. Road repairs are planned for $n^{2}$ days. On the $i$-th day of the team arrives at the $i$-th intersection in the list and if \textbf{none} of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads. According to the schedule of road works tell in which days at least one road will be asphalted.
To solve the problem one could just store two arrays $hused[j]$ and $vused[j]$ sized $n$ and filled with false initially. Then process intersections one by one from $1$ to $n$, and if for $i$-th intersections both $hused[h_{i}]$ and $vused[v_{i}]$ are false, add $i$ to answer and set both $hused[h_{i}]$ and $vused[v_{i}]$ with true meaning that $h_{i}$-th horizontal and $v_{i}$-th vertical roads are now asphalted, and skip asphalting the intersection roads otherwise. Such solution has $O(n^{2})$ complexity.
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; const int N = 100; bool u[2][N]; int n; int main() { cin >> n; for (int i = 0; i < n * n; ++i) { int h, v; cin >> h >> v; --h, --v; if (!u[0][h] && !u[1][v]) { u[0][h] = true; u[1][v] = true; cout << i + 1 << " "; } } puts(""); return 0; }