CF1702 C, D, E, F Solutions
The content below was generated entirely by machine translation. Please verify its accuracy. If anything is unclear, consult the Chinese source version.
C. Train and Queries
Problem statement
Problem links: (Codeforces, Luogu).
You are given an array of length representing all train stations. A train can travel only from a station on the left to a station on the right. In other words, it starts at , then proceeds to , and finally reaches .
You are then given queries. Each query contains two integers and and asks whether it is possible to board at station and travel by train to station .
For example, suppose the array is and there are the following three queries:
- .
It is possible to travel from station to station along the route . - .
There is no route that travels from station to station . - .
There is no route from station to station , because station does not exist at all.
Approach
We only need to know the position where a station first appears and the position where it last appears. Suppose station first appears at and last appears at , and consider a query .
As long as , it is certainly possible to travel from station to station . We know that the first occurrence of station lies to the left of the last occurrence of station , and the train travels only from left to right, so it can reach .
We need a mapping from station numbers to positions. Station numbers can be large, up to , while the number of distinct station numbers is relatively small, at most . An ordinary array is therefore unsuitable because it would consume far too much space. Two possible solutions are coordinate compression by sorting or the use of a map.
Here I use two map objects. One maps each station number to the position of its first occurrence, while the other maps it to the position of its last occurrence, exactly as described above.
This gives us the following code.
Code
Because the program uses cin and cout, slow input may cause a TLE, so synchronization can be disabled.
1 | // author: ttzytt (ttzytt.com) |
D. Not a Cheap String
Problem statement
Let be a string consisting of lowercase Latin letters. Its price is defined as the sum of the positions of all its letters in the alphabet.
For example, the price of the string is .
You are given a string and an integer . Remove as few letters as possible from the string so that the price of is at most . Note that you may remove no letters, or you may remove every letter in the string.
Approach
This problem is actually about as difficult as the previous one. Since the problem asks us to delete as few letters as possible, we directly choose letters that contribute the most to the price and delete them until the total price becomes at most .
For the implementation, we can again use a map to create a mapping from each character to its number of occurrences—in other words, a bucket.
We then traverse this map in reverse order, so the characters visited first make the greatest contribution to the price. During the traversal, if the current price is greater than , we delete the current character. Whenever we delete a character, we also decrement its occurrence count by one.
Finally, to produce the output, we traverse the original string. If the corresponding character still has an occurrence in the bucket, we output it and decrement the remaining count; otherwise, we omit it.
Code
1 | // author: ttzytt (ttzytt.com) |
E. Split Into Two Sets
Problem statement
You are given pairs, where is even and . Every number in every pair is between and .
Determine whether these pairs can be divided into two sets such that no number is repeated within either set.
For example, consider the four pairs .
They can be assigned as follows:
- The first set contains the pairs and , while the second set contains and .
Approach
At first glance, this looks like a greedy problem: put a pair into the first set whenever possible; if that is impossible, put it into the other set; if neither placement works, output . However, this is an E problem, so it is not that simple. (Do not copy me by submitting a greedy solution immediately and then spending ages wondering why it is wrong.)
To prove that this greedy method is wrong, we only need a counterexample. As an aside, the samples for this problem are rather misleading because the greedy method passes all of them.
Consider the following input:
1 | 6 |
Suppose the first set is and the second is . Under the greedy approach, the first two pairs, and , can be placed into . At the third pair, the in conflicts with the in , so we put that pair into .
For the fourth pair , however, we find that it conflicts no matter which set receives it.
Nevertheless, this input can legally be divided into two sets:
We can break each pair apart and consider its individual numbers.
Start with . Two of the pairs contain : and . Because both pairs contain , they certainly cannot belong to the same set.
Apply the same reasoning to . The two pairs containing are and , so they must also belong to different sets.
Listing the pairs that contain each number from through in this way gives:
When we check these conditions, no contradiction appears, and the assignment shown earlier can be derived from them.
Viewed this way, the problem tells us that two objects must be in different sets and asks whether all such rules can be satisfied. Is that not precisely a disjoint-set union structure with logical relationships?
If you are not familiar with this technique, you can look at these problems:
Indeed, this problem can be solved with a disjoint-set union structure that maintains logical relationships; this is how tourist solved it.
However, we can also approach it from the perspective of graph theory.
If we connect the two numbers in every pair with an edge, we obtain a graph like this:
1 | 1 <--> 2 <--> 3 |
For the same reason as before, consider a number such as . The two pairs containing , namely and , cannot be placed into the same set.
In terms of edges, vertex is incident to two edges, and we cannot select both of those edges for the same set.
The only way to meet this requirement is therefore to assign the edges alternately to the two sets.
For example:
1 | 1 <--> 2 <==> 3 or 1 <==> 2 <--> 3 |
Here, edges drawn as <--> and edges drawn as <==> represent the two different sets to which the pairs of endpoint vertices will be assigned.
We can now consider separately whether different graph shapes meet the requirement.
First, if a vertex is incident to three or more edges, alternating between the two sets is impossible.
For example:
1 | A |
To place the three edges to into two sets, at least one of the pairs and , and , or and must belong to the same set. This violates the alternating requirement because inevitably appears twice in that set.
Second, if a connected component is only a path, alternating its edges between the two sets always satisfies the requirement.
Finally, if a component is a cycle with an even number of edges, as in the earlier example, its edges can certainly alternate. A cycle with an odd number of edges cannot satisfy the condition.
The parity of a cycle can be checked rather directly. Give each edge a color chosen from two colors, and use DFS to traverse the cycle.
During traversal, try to color consecutive edges alternately. If this alternating coloring fails, the cycle must be odd, and the converse is also true. If the edges can be colored alternately, the two colors must occur equally often, so the cycle must be even.
There is one more implementation detail to note. The graph we construct is not necessarily connected, so we must attempt a DFS from every vertex. In addition, constructing the graph directly from the input can produce parallel edges, which we need to avoid.
Code
Overall, the code is fairly concise.
1 | // author: ttzytt (ttzytt.com) |
F. Equate Multisets
Preface: the solution in this explanation refers to this video.
Problem statement
A multiset is a special kind of set whose elements may repeat. Like an ordinary set, the order of its elements does not matter. Two multisets are equal when every element occurs the same number of times in both.
For example, and are equal, whereas and are not.
You are given two multisets and , each containing integers.
In one operation, you may double one element of or halve it with rounding down. In other words, for an element of , you may perform either of the following operations:
- Replace with .
- Replace with .
Note that no operation may be performed on multiset .
Determine whether multiset can be made equal to after any number of operations, including zero operations.
Some properties
The operations and correspond to bitwise left and right shifts. For example, the binary representation of is , while that of is . Compared with , the binary form of has an additional at the end. Conversely, is , whose binary representation has one fewer trailing than that of .
Thus, shifting left is equivalent to multiplying by two, and shifting right is equivalent to floor division by two.
From this we can observe a property: trailing zeroes of elements in multisets and are unimportant. Strictly speaking these are multisets, but I will call them sets here for convenience.
I will explain both what a trailing zero is and what “unimportant” means.
Consider the number , whose binary representation is . The binary form of has three zeroes at its end. These three zeroes are the trailing zeroes of .
By “unimportant,” I mean the following.
Let and , and let and be the numbers obtained from and , respectively, after removing their trailing zeroes. If the two allowed operations can transform into , then they can also transform into .
This is because left and right shifts can append any number of zeroes to the end of or remove any number of them.
We can therefore turn back into . We already know that can be transformed into . After that, removing some zeroes from the current number yields .
For convenience in the subsequent computation, we can therefore strip all trailing zeroes from the input elements immediately.
There is another property:
We can transform into if and only if the binary representation of is a prefix of the binary representation of .
First, let us clarify what a prefix means for a binary representation. Consider the numbers and , whose binary forms are and , respectively.
From the perspective of strings, is a prefix of . The reason can be transformed into is the right-shift operation: we may remove bits from the end of until it becomes any prefix of its own binary representation.
It is also evident that if , then cannot be a prefix of the binary representation of . Consequently, cannot be transformed into .
Implementation
With these properties in hand, we can devise a somewhat unusual method.
First, store the elements of multiset in an array and the elements of multiset in a priority queue. Before storing an element, strip its trailing zeroes.
1 | vector<int> a(n); |
Then sort in ascending order. After that, we can perform the following operations:
1 | sort(a.begin(), a.end()); |
As the code shows, on each iteration of this while loop, and are the largest elements currently present in and , respectively.
There are three cases:
- : In this case, we can immediately output
NO, because is certainly not a prefix of the binary representation of , as explained earlier. Moreover, is already the largest element in all of . If cannot be transformed into , no other element of can possibly be transformed into either. - : Since the two elements are equal, both can be removed from their multisets. When the multisets become empty, we can output
YES. This is why the code containsa.pop_back();. - : At this point, we do not know whether is a prefix of , but it might be. We therefore right-shift by one bit, turning it into its longest proper prefix, and later check whether matches another element of .
For the third case, could right-shifting immediately and placing it back into the priority queue destroy a match in which the original could have matched some other element of ?
No. The largest element of is already smaller than , so every other element of is also smaller. Therefore, no other element can be equal to the original value of .
Complete code
1 |
|
As for that final G2 problem, I still have not fully understood it. I am simply not good enough yet…
Finally, I hope this solution article helps you. If you have any questions, you can contact me through the comments or by private message.



![[Stanford CS144] Lab 4 Record](/img/CS144/tcp%E7%8A%B6%E6%80%81%E6%B5%81%E8%BD%AC%E5%9B%BE.jpg)