The programming of the query set:
To explain and query the principles of the set, I will give a more interesting example.
There are thousands of heroes scattered across the world. They have no proper profession. They walk around with a sword all day. If they meet people who are not in the same way as themselves, they will inevitably fight. However, one of the advantages of the heroes is to be loyal and never beat friends of their own. They also believe that "friends of friends are my friends". As long as they can be connected by friends, no matter how many turns they turn, they all think they are their own people. In this way, the rivers and lakes form a community, which is connected by the relationship of friends between the two. People who are not in the same community cannot connect with friends in any way, so they can rest assured that they will die. But how do two people who are not familiar with each other determine whether they belong to a circle of friends? We can cite a famous person in every circle of friends as a representative of this circle, in this way, each circle can name "The Friends of Zidane" and "The Friends of Ronaldo "...... The two can determine the relationship between the enemy and friends as long as they match each other's team leaders.
But there is still a problem. The heroes only know who their friends are. Many people do not know the team leader at all. They need to determine who their team leader is, "Are you the captain? Are you the captain ?" In this way, the captain's face is lost, and the efficiency is too low, and may fall into an infinite loop. The captain ordered a new team. All members in the team adopt a hierarchical system to form a tree structure. Our team leader is the root node. Below are level 2 members and Level 3 members respectively. Everyone just needs to remember who their superiors are. When judging the enemy and friends, you only need to raise the question layer by layer until the highest level, you can determine who the captain is in a short time. We only care about whether two people are connected. It doesn't matter how they are connected, how they are connected, and what the internal structure of each circle is, or even who the team leader is. So we can let the Captain reteam at will, as long as there is no mistake in the relationship between friends and enemies. As a result, the school came into being.
Next let's look at and check the implementation of the Set.
Int pre [1000];
This array records the superiors of every hero. The heroes start from 1 or 0 (based on the Question). If pre [15] = 3, the upper level of the 15th hero is the 3th hero. If a superior is his own, it means that he is the manager, so far. There are also independent people, such as Ouyang Feng, then his superiors are his own. Everyone recognizes their superiors only. For example, Hu qingniu only knows that his superior is Yang Zuo. Who is Zhang Wuji? No! If you want to know who your boss is, you can only query it at the level.
The find function is used by the manager. It makes sense again (the path compression algorithm does not matter, but will be discussed later ).
Let's take a look at the join function, that is, to connect a line between the two points, so that all the points of the original two sections can be interconnected. This is easy to do on the graph. Just draw a line. But now we use the lookup set to describe the situation in the martial arts. There is only one pre [] array. How can we implement this?
Let's give an example of the current situation in martial arts. Xiao Zhu's Monk and Zhou xiaomuo's mm are two people I like very much. Their ultimate boss is Xuan cifang's and the extinct Division's, which are obviously two camps. If I don't want them to fight each other, I will say to them, "You Two Are pulling a hook, be a good friend ." They agreed on my face. This can be done together with Xiao Ke, And the whole Shaolin and Emei can no longer fight. How can we implement such a major change? How many changes do we need? In fact, it is very simple. I said to Xuan cifangzhang: "Master, please change your superiors to an extinct teacher. In this way, the ultimate boss of all the original members of the two schools is the teacher, so I still play a ball! We only care about connectivity, and the internal structure of the school doesn't matter ." Xuan ciyi certainly got angry: "I rely on it. Why did I become her employee? Why didn't I turn it back? I protest !" The protest is invalid. It was arranged by heaven. In any case, the effect is the same for anyone who joins the project. What does this function mean?
Let's take a look at the path compression algorithm. The process of building the school is to use the join function to connect two people, who are totally random. I can't predict what kind of tree structure will become. It is also possible to have a sn. In this way, the search efficiency will be relatively low. The ideal situation is that all direct superiors are in charge, and there are two levels of structure in total. You only need to find the manager once. Even if it cannot be done completely, it is best to approach it as close as possible. In this way, the path compression algorithm is generated.
Imagine a scenario where two heroes meet each other and want to know if they can beat each other.
So I quickly called my superiors and asked, "Are you the manager ?"
The superior said, "I am not, who is my superior and who is, please ask him ."
All the way down, the boss of the two was originally Cao gonggong of the East factory.
"Oh, it turns out to be a self-remembered person, Xi lixi ceremony. There are six groups of white gourd dolls in the next three camps !"
"Fortunately, we are lucky to have a bunch of fairy dog tails and flowers in the ninth camp !"
The two went drinking with pleasure.
"Wait a moment. Please leave the two students for a while. There are still some unfinished work !" I want to stop them.
"Oh, by the way, we still need to compress the path ." The two were awakened.
White-faced huluwa called his parent six leaders: "I have checked the team lead. Cao gonggong is the director of his study couple. It's better for me to work together and worship them under Cao gonggong. the province's level is too low, so I will find the manager in the future ."
"Well, it makes sense ."
The white-faced gourd doll then called the three battalion leaders who just visited ...... The fairy dog's tail and flower have done the same thing.
In this way, all the involved figures in the query are under the direct leadership of Cao gonggong. Each query is optimized, so the number of layers of the school tree remains relatively low. The code for path compression can be well understood and can be copied and used directly. In short, the functions it implements mean this.
The most typical example of querying a set is the food chain.
Poj 1182 food chain
Http://acm.pku.edu.cn/JudgeOnline/problem? Id = 1182
The question tells you that there are three animals that eat and are eaten each other. Now I will tell you m sentences, in which there are true and false ones. Tell you to judge the number of false ones (if there is no conflict with the current one, that is, it is regarded as the truth)
There are several ways to use this question. My previous practice is that each set (or called a subtree, the number of the set is equivalent to the root node of the subtree, a concept) has its own elements divided into, class B and class C: change the type of the root node when merging, and change the offset for other points accordingly. However, this formula is difficult to push, especially the offset is easy to calculate incorrectly.
The following describes a common and easy-to-understand method:
First, we record the relation between each vertex in the Set and the root node of the Set (or subtree. 0 indicates that it is similar to the root node, 1 indicates that it eats the root node, and 2 indicates that it is eaten by the root node.
Then, to judge the relationship between two vertices A and B, we make P = find (A), q = find (B), that is, p and q are respectively, the root node of the B subtree.
1. If P! = Q indicates that A and B are irrelevant for the time being, so their judgment is correct, and then the two Subtrees are merged. Here is the key. How can we merge two Subtrees so that the new merged tree can be correct? Here we stipulate that only P can be merged into q (as we have just said, the optimization effect of heuristic merge is not that obvious. If we use heuristic merge, we should introduce two formulas, this is a very tiring task... so we generally specify that one subtree is merged into another subtree ). After the merge, the relation of P must be changed. How much should it be changed? The method here is to find the rule and list some possible cases, so we can launch the formula. The formula is tree [p]. relation = (tree [B]. relation-tree [A]. relation + 2 + d) % 3; here, D is the relationship between A and B in the judgment statement. Another question is, do we need to traverse the entire a subtree and update the status of each node? The answer is no, because we can slightly modify the find () function, that is, node x inherits its father (note that it is the former father, because the father will change after the path is compressed ), that is, it will inherit the changes to the P node, so we do not need to traverse the previous update for each.
2. If P = Q, it indicates that A and B have been related before. Then we will determine whether the statement is correct, and look for a regular expression. That is, if (tree [B]. Relation + D + 2) % 3! = Tree [A]. relation), then this sentence is incorrect.
3. then, modify the find () function to record the father before the path compression, and then update the state of the path after the path compression (by inheriting the state of the former father, at this time, my father's status was updated ).
The two core functions are:
Int find (int x)
{
Int temp_p;
If (tree [X]. parent! = X)
{
// Because of path compression, the relationship between the node and the root node needs to be updated (because the previous merge may not be updated yet ).
Temp_p = tree [X]. parent;
Tree [X]. Parent = find (tree [X]. Parent );
// The relationship between x and the root node is updated (because the root node has changed). At this time, temp_p is the root node of the original subtree.
Tree [X]. Relation = (tree [X]. Relation + tree [temp_p]. relation) % 3;
}
Return tree [X]. parent;
}
Void Merge (int A, int B, int P, int Q, int D)
{
// The formula is derived from the law.
Tree [p]. Parent = Q; // The subscript here is the same, all of which are tree [p].
Tree [p]. Relation = (tree [B]. Relation-tree [A]. Relation + 2 + d) % 3;
}
This method of recording the relationship with the root node is suitable for almost all the queries to determine the relationship between the Set (at least I have never encountered any unsuitable situation... It may be that you do too little ...), Therefore, we strongly recommend that you ~~
After the problem of the food chain is fixed, most of the basic questions in poj can be queried in seconds. Here, only one question number is listed:Poj 1308 1611 1703 1988 2236 2492 2524.
Next we will explain several questions that are slightly improved:
Poj 1456 supermarket
Http://acm.pku.edu.cn/JudgeOnline/problem? Id = 1456
The greedy idea of this question is obvious, but the complexity of O (N ^ 2) is obviously not good. We can use heap for optimization, here we will discuss and query the optimization methods of the Set (very clever ). We regard continuous occupied intervals as a set (subtree), and its root node is the first unoccupied interval on the left of this interval.
Sort first, and then judge whether find (B [I]) is greater than 0 each time. If it is greater than 0, it indicates that there is still unoccupied space on the left, it will be occupied, and then merge (B [I], find (B [I])-1. Similarly, we stipulate that only the left subtree can be merged to the right subtree (think about why ~~).
Poj 1733 parity game
Http://acm.pku.edu.cn/JudgeOnline/problem? Id = 1733
This question also uses the idea similar to the food chain.
First, we first discretization, because the original range is too large (10 ^ 9), we can discrete it into (10 ^ 4) according to the number of problems ). We need to understand that the discretization here does not affect the final result, because the parity number of 1 in the interval has nothing to do with the size of the interval (this sentence is a bit strange and can be ignored ...), then input a and B each time. We put B ++. if they are in a set, the number of 1 in the range [a, B] is equivalent to B. relation ^. relation, right or wrong. If it is not in a set, merge the Set (Here we stipulate that the child tree with a small root node is merged with a large root node, so we need to push the form according to different situations ), modify the status of the root node of the subtree. Other node statuses of the subtree are updated using the find () function.
HDU 3038 how many answers are wrong
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 3038
The enhanced version of the question above does not need to be discretization, because the range is related to the range size (compared with the above sentence, it can also be ignored ...), The practice is similar to the above question, but the style has changed and you can simply push it yourself. But there is another condition for this question, that is, the value of each vertex is between [0,100]. If A and B are not in a subtree, We will merge them, however, before merging, you must determine whether the merge statement will make the range and the merge statement invalid. If the merge statement is invalid, the merge statement will not be merged and the statement is incorrect.
Poj 1417 true liars (hard)
Http://acm.pku.edu.cn/JudgeOnline/problem? Id = 1417
And query set + dp (or search ).
The question tells two types of people, one is to tell the truth, and the other is to say lies. Then I will tell m statements and ask if I can determine who are the ones who tell the truth.
As a matter of fact, it is still similar to the food chain to check the collection unit, and it is easier to reduce the number of types. We can merge related persons into a collection through the query set (For details, refer to the instructions on the food chain ).
The current problem is that there are n sets, each of which has a and B Numbers. Now we need to jump out of one number (A or B) for each of the N sets ), so that the sum of them is equal to N1 (the number of people who tell the truth ). However, this solution can be well solved by using DP. f [I] [J] indicates the sum of the I-th set and J-th, we have also used pre [I] [J] to record whether A or B is selected and used to judge the status later. The equation is f [I] [J] = f [I-1] [J-A] + F [I-1] [J-B], j> =, j> = B. If f [N] [N1] = 1 indicates a unique situation, output this situation; otherwise, output "no" (Multi-solution no)
Note:
1. The M, N1, and N2 values of this question may all be 0, which can be processed specially or together.
2. According to the above DP statement, F [I] [J] may be very large, because n can reach three digits. In fact, we only care about three situations where f [I] [J] is equal to 0, equal to 1, and greater than 1. Therefore, when f [I] [J]> 1, let's make it equal to 2.
Poj 2912 rochambeau (hard)
Http://acm.pku.edu.cn/JudgeOnline/problem? Id = 2912
Baidu star 2006 Preliminary's question is very good, and it is difficult to query questions. In fact, this question is completely related to the food chain, the same three types of food, and the same mutual constraint. Therefore, you do not need to modify the food chain code. However, this question has a judge that can be used as a gesture. So our practice is to enumerate every child as judge, when judging him as a judge, the first sentence of err [I] (that is, the first sentence can judge whether the child is not a judge ).
1. If only one child is judge, all the statements are correct, indicating that the child is judge, then the number of sentences judged is the maximum value of err [I] of other children. If
2. If every child does not use judge (that is, the wrong statement can be found), it is impossible.
3. When more than one child is judge, no error statement is found, that is, can not determine.
Zoj 3261 connections in Galaxy war
Http://acm.zju.edu.cn/onlinejudge/showProblem.do? Problemid = 3563
NUAA 1087 Unicom or unconnected
Http://acm.nuaa.edu.cn/acmhome/problemdetail.do? & Method = showdetail & id = 1087
The practice of the two questions is similar. Both of them are reverse and query the set questions. Sort the edge set first, and then mark the edge to be deleted from the two points in the edge set. Then, check the edge set that is not marked by the set connection, and then perform reverse query. When the first question is merged, it can be merged based on the priority required by the question.
The questions about and query sets are mainly used to process the relationship between sets (this is the housekeeping skill of the query set ~~), As for the function of querying datasets, it is still useful in the Kruskal Algorithm for Finding the minimum spanning tree. That is the problem of finding the Minimum Spanning Tree in graph theory. (generally, this difficulty is not to look up the set, it is just a method used to find the Minimum Spanning Tree ~~
Share from tina_z_y and czyuan