Let’s see when does mex([ai,ai+1,ai+2]) equal max([ai,ai+1,ai+2])−min([ai,ai+1,ai+2]).
Case 1:mex([ai,ai+1,ai+2])=0
This implies that all numbers are equal and non-zero, since otherwise min would be less than max and the difference wouldn’t be 0.
Case 2:mex([ai,ai+1,ai+2])=0
In this case min([ai,ai+1,ai+2]) should be 0 because 0 is in the sequence. So mex([ai,ai+1,ai+2])=max([ai,ai+1,ai+2]) but this is not possible, since mex([ai,ai+1,ai+2]) should not be among ai, ai+1, or ai+2.
So an array is good if all elements are equal and non-zero. Remove every −1 from a, then check whether all remaining elements are equal and non-zero.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<bits/stdc++.h>
usingnamespace std;
intmain(){ int tc; cin >> tc; while (tc--) { int n; cin>>n; vector<int> v(n); for (int i = 0; i < n; i++) cin >> v[i]; set<int> s(v.begin(), v.end()); s.erase(-1); if (s.size()<=1 && !s.count(0)) cout<<"YES"<<endl; else cout<<"NO"<<endl; } }
The answer to the problem only depends on x, n, the index of the wall Hamid would hit if he moves to the left, and the index of the wall he would hit if he moves to the right.
Hint 2
If we denote the two indices defined in Hint 1 as L and R, then in each of Hamid’s turns, he can move in a way that ensures by the next time, either L has decreased by at least one, or R has increased by at least one, regardless of Mani’s moves. So, if it’s Hamid’s turn, what is the maximum possible answer in terms of L, R, and n?
Answer
The answer is at most min(L+1,n−R+2).
Solution
Suppose it’s Hamid’s turn. If there is no wall to his right or to his left, he can escape the grid in one move. Otherwise, define:
L as the index of the wall Hamid would reach if he moves to the left.
R as the index of the wall he would reach if he moves to the right.
Hamid can move to the left and decrease L by at least one. (Since L is always to the left of Hamid’s current position, when Hamid moves left, he reaches and destroys the wall at position L. As a result, on his next turn, the new L will be at least one position further to the left. meaning L decreases by at least one, regardless of Mani’s actions.) Similarly, Hamid can increase R by at least 1 by moving to the right and destroying the wall there.
So, since Hamid wants to escape in the minimum number of moves, he can escape the grid in at most min(L+1,n−R+2) moves.
On the other hand, with each of Hamid’s moves, Mani can place a wall in such a way that L decreases by at most one or R increases by at most one.
So the minimum number of moves Hamid needs is also min(L+1,n−R+2).
Therefore, assuming Hamid starts first, the answer is min(L+1,n−R+2).
Now consider Mani’s first move. Since Mani wants to maximize the number of days Hamid needs. Moreover, with each of his moves, at least one of the L or R remains unchanged. So, on his first move, he can:
maximize L+1 by setting L=x−1, or
maximize n−R+2 by minimizing R, setting it to x+1.
So the answer becomes either min((x−1)+1,n−R+2) or min(L+1,n−(x+1)+1).
Because Mani wants the number of days to be as large as possible, the final answer is: max(min(x,n−R+2),min(L+1,n−x+1))
We can easily find L and R with a time complexity of O(n). Therefore, the problem is solved in O(n) time complexity.
We can see that permuting arrays a and bin the same way or changing ai with bi for a specific index i doesn’t change the answer. WLOG assume ai≤bi is always true.
Hint 2
Imagine Ali selects indices i and j in a round of game. What are all the different new arrays Bahamin can achieve?
Can Ali ever achieve a value less that the initial value?
Answer
He can’t. Because Bahamin can always keep the chosen indices as they are, and so the value won’t change. No matter what Ali does.
Solution
Read the hints.
Let’s first address hint 2. To determine all arrays that Bahamin can reach, WLOG assume ai≤bi≤aj≤bj. The specific order doesn’t matter, since Bahamin can permute them freely. Set x1=ai, x2=bi, x3=aj, x4=bj — this makes the following cases reachable for Bahamin:
Other cases are similar (based on Hint 1). We observe that the second and third options yield the same value, while the first option is exactly 2×(x3−x2)less than the other two. There are now two possible cases:
Case 1: Ali can choose two indices i and j such that the ordering of [ai,bi,aj,bj] already matches one of the second or third options. In this case, Bahamin cannot increase the value when he is initially given indices i and j. Since Ali also cannot reduce the value, his optimal strategy is to always give Bahamin such indices so that the final value remains equal to the initial value.
Case 2: Ali cannot find any two indices i and j that match the second or third option. This implies that for every pair of indices i,j, either b_i < a_j or b_j < a_i. We claim the answer is \sum\limits_{i=1}^{n} (b_i - a_i) + \min\limits_{1 \leq i, j \leq n, \space b_i < a_j} (2 \times (a_j - b_i)).
A strategy for Ali is to always select the two indices i,j such that b_i < a_j and the difference aj−bi is minimized. Bahamin can increase the value only once — when he changes the configuration of indices i,j from the first option to either the second or third option. We know this increases the initial value by exactly 2×(aj−bi). Also, it’s impossible for Ali to force any value lower than this. Since regardless of Ali’s selection, Bahamin can always change it to the second or third option, and by definition, any choice by Ali gives Bahamin a chance to increase value by at least our claimed amount. Also Bahamin should skip his turn (i.e., make no changes) on all subsequent turns after the first.
Now to calculate the answer so that it fits the time limit, let’s first represent our array as a set of n segments of the form [ai,bi] on the number line. An interesting property of this representation is that the first option now corresponds to two completely separate intervals, while the second and third options correspond to two intersecting intervals.
Now finding the answer becomes relatively easy. Sort the intervals by their left endpoint. If there are two neighboring intervals that intersect, then the input satisfies the Case 1 condition, and so the answer is the initial value. Otherwise, we observe that all pairs of intervals are non-intersecting, and thus the input satisfies the Case 2 condition. The answer, based on Case 2 and our earlier definitions, is 2×(distance between closest two segments)+(initial value).
The two closest intervals must also be adjacent after sorting by their left endpoint. So, by computing the minimum distance between each pair of neighboring intervals, we obtain a solution in O(nlogn).
Code
Bonus
There were completely different versions of this problem at first.
The original version was that Ali and Bahamin would take turns, and on each turn, a player would perform both operations described in the problem. Their goals and the constraints were similar to what is stated in the final version of the question.
We can prove that the map of Destinyland contains no cycles.
Hint 2
Take a look at the map below:
Hint 3
Prove that a tree can be a valid Destinyland map if and only if it does not contain a subtree that looks like the one shown in Hint 2.
Hint 4
If we remove all the leaves from the Destinyland tree, the remaining graph forms a simple path.
Solution
Let G be the graph of the Destinyland map.
If there exists a subgraph H of G that cannot be a valid Destinyland map, then G itself cannot be valid either.
To prove this, assume, for contradiction, that G is valid but H is not. Then, by removing the vertices and edges not in H, we get a subgraph H that should also be valid. But it isn’t! This contradicts our assumption, so G cannot be valid either.
Lemma 1: A cycle of any length cannot be a valid Destinyland map. Proof: Assume the opposite. Let v be the leftmost house on the northern side. It has two neighbors on the southern side. Let the one on the left be L and the other one R. Since L must have another neighbor besides v, that neighbor cannot be on the southern side, so it must be on the northern side. However, since v is the leftmost node, this neighbor must be to the right of v, and the edge between L and this neighbor would cross the edge v—L. This contradiction shows that L cannot have another neighbor besides v, which contradicts our assumption that the graph is a cycle.
Lemma 2: The following tree cannot be a valid Destinyland map: Proof: Vertices 2, 3, and 4 are all on the side opposite vertex 1. If we place them in order from left to right as u1, u2, and u3, then the neighbor of u2 will necessarily create a crossing either with edge 1—u1 or 1—u3. Therefore, it is impossible to arrange the vertices of this tree in a valid Destinyland layout.
From Lemma 1 and Lemma 2, we conclude that:
G must be a tree.
No vertex in G can be connected to three or more non-leaf neighbors.
Now, remove all the leaf nodes. Since these leaves are always non-cut vertices (i.e., their removal doesn’t disconnect the tree), the remaining graph, if it exists, is still connected. Since all remaining vertices have degree at most 2. So the resulting structure must be a path.
Case 1: The graph becomes empty after removing leaves.
In this case, the original graph was just a single edge. So the answer is simply 2.
Case 2: Only one vertex remains.
In this case, the original tree was a star. Depending on which side we place the central vertex, and how we permute the leaves, the answer is: 2×(n−1)!
Case 3: Two connected non-leaf vertices u and v remain.
In this case, there are 4 valid placements depending on which one is on the northern side and how their adjacent leaves are arranged around the other. ( Note: It’s impossible for either u or v to have neighbors on both sides of the other.)
So the answer is: 4×(du−1)!×(dv−1)! where du and dv are the degrees of u and v, respectively.
Case 4: The remaining structure is a path of length at least 3.
In this case, we have 4 valid ways to place it. These depend on which vertices are placed on the northern side, and how the two vertices from one side with at least two vertices are positioned. (Since the path has at least 3 vertices, there’s no conflict.)
Now, we only need to arrange the leaves adjacent to each vertex relative to each other. Because their positions relative to the other vertices depend only on the four ways to arrange the main path. The proof of that is boring, so we won’t bore you with it :)
Let S be the set of vertices on the path, and let Sahai be the number of leaves connected to vertex i. Then the total number of valid layouts is: 4×r∈S∏(Sahar!)
To implement the solution:
Check if the input graph is a tree.
Verify that no vertex has more than two non-leaf neighbors.
Count the number of non-leaf vertices.
Based on that count, determine which case applies and compute the answer accordingly.
int32_tmain(){ cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); fact[0] = 1; for (int i = 1; i < MXN; i++) fact[i] = (1ll * fact[i-1] * i) % MOD; int T; cin >> T; while (T--) { cin >> n >> m; for (int i = 1; i <= n; i++) adj[i].clear(); for (int i = 1; i <= m; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); }
longlong ans = 2; int tl = 0; if (m >= n) ans = 0; for (int u = 1; u <= n; u++) { if (adj[u].size() > 1) { int x = 0; for (int v : adj[u]) { x += (SZ(adj[v]) == 1); } if (x >= SZ(adj[u]) - 2) (ans *= fact[x]) %= MOD; else ans = 0; } else tl ++; } if (tl < n-1) tl = 2; else tl = 1; cout << (ans * tl % MOD) << '\n'; } return0; }
There are some vertices that will always be cutie, no matter how the other vertices are colored. What are these vertices?
Hint 2
We can show that there exists a coloring where only the vertices mentioned in Hint 1 become cutie. So, the final answer is the sum of the weights of the vertices mentioned in Hint 1.
Solution
Read the hints.
We will use a very useful and interesting technique called the Virtual Tree (or Auxiliary Tree). You can learn more here: Virtual Tree. There are other solutions to this problem, but they use a similar core idea.
The virtual tree of a set of vertices like S is defined as this set:
A=S∪{lca(u,v)∣u,v∈S}
Now let’s build this virtual tree for the vertices of each color separately. After this, all vertices fall into three categories:
Vertices that are in no virtual tree.
Vertices that are in exactly one virtual tree.
Vertices that appear in more than one virtual tree.
Every vertex like u of the third type will definitely be cutie, because no matter what color it is assigned, at least one of the colors of the virtual trees it belongs to will be different from u's color.
So the answer is at least the sum of the weights of all type-3 vertices.
To construct an example with exactly this answer, run a DFS algorithm. Every time you enter a vertex u, consider the following cases:
It’s type 2. In that case, color it with the color of the virtual tree it belongs to.
It’s type 3. In that case, color it with any color from its subtree (such a color exists by definition). This vertex is cutie anyway.
It’s type 1 and there is some colored vertex in its subtree. Then color this vertex with that color.
It’s type 1 and its entire subtree is uncolored. In that case, color this vertex with its parent’s color.
To prove this coloring is valid, observe that coloring a vertex u with a color from its subtree does not make any new vertices cutie (because any such vertex would already have become cutie due to the same color in u's subtree). Also, no vertex strictly inside u's subtree changes status. And u itself doesn’t increase the cost based on how we chose its color.
Now, for the case where we color u with its parent’s color: if any new cutie vertex appears, it must be the parent. But since both have the same color, there’s no additional cost.
Also, in this constructed example, we never introduce any new colors. So all colors stay within the range [1,k].
Therefore, the final answer is always the sum of the weights of type-3 vertices—those that appear in more than one virtual tree. These virtual trees can be constructed in O(nlogn).
f(a) is the sum of maximums minus the sum of element right after a maximum minus a1.
Hint 2
Fix the maximum. How to count the sum of maximums?
Hint 3
You need to solve the following sub-problem:
You are given three integers n, m, and x. How many arrays a1,a2,…,an exists such that:
0≤ai≤x for all 1≤i≤n
a1+a2+…+an=m
Hint 4
The sub-problem can be solved in O(m/x) using inclusion exclusion.
Hint 5
How to count the sum of an specific element in the sub-problem of Hint 3?
Solution
Observation:f(a) is the sum of maximums minus the sum of element right after a maximum minus a1.
Proof
Suppose that 1=i1<i2<…<ik=n is the indices that we visit in the algorithm, and 1≤j1<j2<⋯<jt=k is the indices such that aijp is maximum for all 1≤p≤t.
Consider the following graph: i→pi. We will see the permutation as the graph.
When asking a permutation q, the result is sum of whether q^{-1}(i)<q^{-1}(p_i).
Hint 1
Why is there a condition about k? If we do not have k, can the permutation [2,1,4,3] be guessed out?
Hint 2.1
When we ask a permutation, what does asking the reverse of the permutation help us with?
Hint 2.2
If we ask the reverse of the permutation except the index k, how many times is each edge of the permutation graph counted in total?
Hint 3
How to choose k?
Solution
Let x be a number that we have not yet fixed, and let k=x+1.
This partitions the array into three segments:
$ \begin{aligned} A &= [1, x] \ B &= [x + 2, n - x] \ C &= [n - x + 1, n] \end{aligned}$
This tripartition helps in controlling the query behavior.
Queries:
Say we want to find out who maps to vertex i, i.e., find j such that pj=i.
Here’s how:
Construct a permutation q such that qk=i
Query this permutation → receive answer a
Reverse all elements of qexcept the position k
Query the reversed permutation → receive answer b
If we consider the permutation graph of p:
Any edge not involving i contributes once to the total count. Why?
The edge where pj=i:
Will not be counted if j=qk. This is not possible because it is guaranteed in the question that pi=i.
Will be counted in only one of the two queries if j∈q[A∪C].
Will be counted neither if j∈q[B].
The edge where pi=j will not be counted at all, because i is at index k.
Thus, a+b is one of [n−2,n−1] and by comparing a+b, we can find which segmentj (the predecessor of i) lies in.
Repeating the Process:
Once you know the predecessor is in a certain half, you repeat:
Repartition the candidate set into two
Choose one half to be placed in A∪C, and the other in B (If we had enough capacity).
Place i at index k again.
Do the same query + reverse trick
Choosing k:
If we set x=⌊4n+1⌋,k=x+1, with each iteration (both in the first query and in the rest of the queries) the size of the candidate set shrinks by a factor of 2.
So to find the predecessor of one number i, we need 2log(n−1) queries.
To find the entire permutation of n elements 2nlog(n−1) queries.
We stay well within the 15⋅n limit.
Code
Bonus
This way can also be implemented with 2log(n−1)+x=1∑n−12logx∼12⋅n queries.
This version used an almost completely different approach from G1. Here’s the step-by-step analysis:
Analysis (Steps & Hints)
Step 0
Consider the following graph: i→pi. We will see the permutation as the graph.
When asking a permutation q, the result is sum of whether q^{-1}(i)<q^{-1}(p_i).
Hint 1.1
Why is there a condition about k? If we do not have k, can the permutation [2,1,4,3] be guessed out?
Step 1.2
If there is a cycle of length 2 in the permutation graph (that is, pi=j and pj=i), exactly one of the two corresponding pairs to (pi,pj) and (pj,pi) will be counted in any query when we do not have k. So we have to use k for cycles of length 2. This inspires us to do casework on cycle length =2 or ≥3.
Step 2.1
If the whole permutation graph is composed only of cycles of length 2, can you guess out the permutation in about 21nlogn queries?
Hint 2.2
You need to use the property that the permutation graph is composed only of cycles of length 2.
Step 2.3
Let’s say you want to determine what is pi. Query any permutation q with qk=i. If pi is among q1,q2,…,qk−1, the response to the query will be 2n, otherwise, pi is among qk+1,qk+2,…,qn, and the response will be 2n−1. You can verify this by yourself. Note that permutation graph is composed only of cycles of length 2.
Thus, we can put k around 2n and apply binary search for a single i→pi with logn queries. Note that when we get pi=j, we also get pj=i. So we only need 21nlogn queries in total.
Step 3.1
How can we distinguish i→pi is in which kind of cycle, length of 2 or length ≥3? Try to solve this for a single i in 2logn queries. Note that you do not need to determine pi, you just need to tell whether i→pi is in a cycle of length 2.
Hint 3.2
If i→pi is in a cycle of length ≥3, we have l and j such that l→i→j and l=j. Otherwise, l=j.
Hint 3.3
Consider bitmasks.
Hint 3.4
Consider cyclic shifts. Do not use k.
Step 3.5
Consider the following two queries (m<k):
[q1,q2,q3,…,qm,…,qk,…];
[qm,q1,q2,…,qm−1,…,qk,…].
Only the contribution of x→qm→y may change: Let’s say A={q1,q2,…,qm−1}, B={qm+1,qm+2,…qn}. If x and y are both inside A or both inside B, responses to query 1. and 2. will be the same. Otherwise, answer changes by exactly 1. If the responses are different, we can next tell whether xi is in A by looking at whether the difference is 1 or −1. However, if the responses are the same, we can’t tell whether they are both in A or both in B.
An idea to tell whether x=y is to group numbers by their bitmasks. We can use logn times such two queries to ask for each bit (let numbers with 0 on this bit in A, those with 1 in B). In the end, we will get x⊕y. Then we surely get whether x=y.
Hint 3.6
Step 3.5 needs 2logn queries for a single element. Can you use nlogn queries to solve the problem in Step 3.5 for all elements? Note that we are doing cyclic shifts.
Step 3.7
Note that we are doing cyclic shifts. In fact, for each i, we just need it to appear at q1 and qm respectively, without changing the set A. Then, for a certain set A, we can do cyclic shifts ∣A∣ times to get all information we need. Similar for B. Thus, we finished the task in Hint 3.6 in nlogn queries.
Since we will fix k around 2n for cycles with length 2, we must ensure that ∣A∣ and ∣B∣ are around 2n. But this is not always true. Fortunately, we can resolve this issue by assigning each integer an unqiue number ci, where 0≤ci≤2⌈logn⌉−1, so that there will be exactly 2n (or floor and ceil) 0s and 1s on each bit. We will group the indices by ci instead. Now we can put k=⌈2n⌉+1.
Final Steps
Here are the final steps of this problem. First, we run the algorithm in Step 3. Now we get all xi⊕pi, where xi→i→pi holds.
First, we will determine all pi-s on cycles of length ≥3. Note that we have determined all xi⊕pi, so we only need to determine one edge for each cycle.
Note that in Step 3, when responses to two queries are different, we can know whether pi is in A or xi is in A. Note that we can change m arbitrarily, so we can apply binary search on m to get one of pi and xi. That finishes the task in logn queries for each cycle. On average for each element, it is at most 31logn queries.
After that, we know all pi-s on cycles of length ≥3, and we can calculate the response to any query [q1,q2,…,qn] easily if we don’t have k. Similar to Step 2, we can determine all pi-s on cycles of length 2 in 21nlogn queries. On average for each element, it is 21logn queries. Thus, in the worst case where the whole permutation graph consists only of cycles of length 2, the total number of queries is 1.5⌈logn⌉⋅n. When n=100, it is 10.5⋅n, a little larger than the limit. We can apply a trivial optimization when doing Step 2: do binary serach on possible indices instead of all indices. This will use a total of at most nlogn+i=0∑⌊(n−1)/2⌋log(n−1−2⋅i) queries. When n=100, it is 986, which fits the constraints well.
Each connected component of a candy graph is either a simple path or a simple cycle.
Hint 1
Try to break the problem down into smaller parts.
Hint 2
Take a DFS tree, at most 5 back-edges pass through each vertex.
Hint 3
Choose a vertex v, brute force on the back-edges that pass through v and appears in the subgraph with maximum number of edges, then remove v and all back-edges that pass through v.
Hint 4
Now we have to solve the following sub-problem for each connected component:
You are given a simple connected graph that each vertex belongs to at most 5 simple cycles, and an array d1,d2,…,dn(0≤di≤2). What is the subgraph with maximum number of edges that degree of vertex i is at most di.
Hint 5
The sub-problem can be solved in O(2nnm) with dp bitmask.
Hint 6
Let N be the size of the component with the maximum size after removing v and back-edges that pass through v.
We can solve the problem in O(252NNm).
Hint 7
Choose v as the centroid of the DFS tree.
Since N≤n/2 the complexity will be O(252n/2nm).
Hint 8
Is the complexity really O(252n/2nm)?
Solution
Each connected component of a candy graph is either a simple path or a simple cycle.
Take a DFS tree, at most 5 back-edges pass through each vertex, then choose a vertex v, brute force on the back-edges that pass through v and appears in the subgraph with maximum number of edges, then remove v and all back-edges that pass through v.
Let di be the maximum degree that vertex i can have. Initially di=2 for each vertex. Each back-edge (x,y) that you select, reduces dx and dy by 1. If after selecting back-edges that pass through v, there exists a vertex with negative d, skip this case. Otherwise you have to solve the sub-problem in Hint 4 for every connected component.
We can solve the sub-problem with the following dp bitmask:
Let ansmask be the answer for mask, and let dpmask,u,v,l1 be the answer for mask where the last path we selected is from u to v and l1∈0,1 means that the length of the path is 1 or not.
Transitions:
Start a new path: ansmask+1→dpmask,u,v,1, if (u,v) is an edge outside mask with du,dv≥1.
Add a vertex to the last path: dpmask,u,v,l1+1→dpmask+2w,u,w,0, if w is a vertex outside mask and adjacent to v, and dv=2,dw≥1.
Make the last path cycle: dpmask,u,v,0+1→ansmask, if there exists a (u,v) edge, and du=dv=2.
Skip a vertex: ansmask→ansmask+2w, if w is a vertex outside mask.
Also, you have to solve the sub-problem for each component twice, because you can choose a DFS tree edge connected to the vertex that you’ve deleted and it reduces d of one vertex in that component.
It can be seen that if N be the size of the component with the maximum size, the complexity will be O(2NNm) for a fixed set of back-edges, and O(252NNm) in total.
If we select v as the centroid of the DFS tree N will be less than or equal to n/2 so the complexity will be O(252n/2nm).
It can be proven that m≤3n in graphs that each vertex belongs to at most 5 simple cycles. So the complexity will be O(252n/2n2).
Proof
We prove this by induction. suppose that m≤3n for all graphs with n<N.
Take a DFS tree, we can prove that the degree of a leaf is at most 3, because otherwise at least 3 back-edges would exit that leaf and there would be at least 6 cycles containing that leaf.
So there always exists a vertex with degree ≤3, we can remove it, m≤3(N−1)+3=3N.
It turns out there are some very simple randomized solutions we hadn’t anticipated, as well as approaches using matching and even unexpected ones like backtracking. Unfortunately, these are quite hard to detect and reject without knowing beforehand.
We sincerely apologize for this mistake. We hope you enjoyed the rest of the problems.