HDU 1232 and query set

Source: Internet
Author: User

HDU 1232 and query set []

This is a trick I learned from experts during the summer vacation. I think it is really a subtle design. In the past, I was able to solve a type of problem that I could not solve in such a simple and efficient way. I am sorry for the party. (Party: I rely on it. Is it my fault? Are you familiar with me ?)

Let's look at an example, hangdian 1232 smooth engineering http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1232

First, we will give you several towns on the map. These towns can all be seen as vertices, and then tell you which roads are directly connected between towns. Finally, we need to solve the connectivity problem of the entire graph. For example, you can randomly give two points for you to determine whether they are connected, or ask you how many connected branches are in the whole graph, that is, they are divided into several independent blocks. If you want to solve this problem, you still need to build several routes. In essence, you need to build several connected branches. If it is a connected branch, it means that the points on the entire graph are connected and no longer need to build the road. If it is two connected branches, you only need to repair one more road, select a vertex from each of the two branches and connect them, then all the points are connected. If there are three connected branches, you only need to repair two more links ......

This set of data input data is described below

4 2 1 3 4 3

The first line tells you that there are 4 points and 2 routes in total. The following two lines tell you that there are routes between 1 and 3, and between 4 and 3. The entire graph is divided into 1-3-4 and 2 parts. Just add another path and connect 2 to any other point to achieve smooth engineering. Then the output result of this set of data is 1. Now, let's program and implement this function. There are hundreds of towns, and there may be loops. How can this be done?

I didn't know it before. Since I used it and checked the set, hi, the effect is really good! Our family uses it!

The query set consists of an integer array and two functions. The array pre [] records the leading points of each vertex. The function find is the query, and the join is the merge.

Int pre [1000];

Int find (int x) {// find the root node

Int r = x; while (pre [R]! = R) r = pre [R]; // path compression

Int I = x; Int J; while (I! = R) {J = pre [I]; Pre [I] = r; I = J;} // return the root node

Return R;

Void join (int x, int y) {// judge whether x y is connected

// If it is connected, you do not need to worry about it. // if it is not connected, merge the connected branches where they are located,

Int FX = find (x), FY = find (y );

If (FX! = FY) Pre [FX] = FY ;}

To explain and query the principles of the set, I will give a more loving 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 ).

Int find (int x) {// find the root node

Int r = x; while (pre [R]! = R) // if my superiors are not leaders

R = pre [R]; // I will look for his superiors until I find the manager.

// Return the root node

Return R; // The Head of the game ~~~

} Let's take a look at the join function, that is, to connect a line between two points. In this way, all the points of the two plates where they were originally located 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?

Void join (int x, int y) // I want to make friends between weizhu and Zhou RuO

{Int FX = find (x), FY = find (y); // xuzhu's boss is Xuan CI,

If MM's boss is extinct

If (FX! = FY) // Xuan Ci and the extinction are obviously not the same person

Pre [FX] = FY; // The Abbot is forced to work as a teacher rather than a teacher.

}

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.

Back to the question raised at the beginning, my code is as follows:

# Include int pre [1000];

Int find (int x ){

Int r = X;

While (pre [R]! = R)

R = pre [R];

Int I = x; Int J;

While (I! = R)

{

J = pre [I]; Pre [I] = r; I = J;

}

Return R;

}

Int main ()

{Int n, m, P1, P2, I, total, F1, F2;

While (scanf ("% d", & N) // read n. If n is 0, end {// At the beginning, there are n towns, there is no path. // you need to build n-1 roads to connect them.

Total = n-1;

// Each vertex is independent of each other and has its own set, ranging from 1 to n // the superiors of each vertex are themselves

For (I = 1; I <= N; I ++) {pre [I] = I;} // a total of M routes

Scanf ("% d", & M); While (M --) {// the following code is actually a join function, but it is slightly changed to meet the requirements of the question.

// Read each path to see if its endpoint P1 and P2 are already in a connected branch.

Scanf ("% d", & P1, & p2 );

F1 = find (P1); F2 = find (P2 );

// If the two branches are not connected, connect them.

// The total number of branches is reduced by 1, and the number of remaining branches is reduced by 1.

If (F1! = F2) {pre [F2] = F1; total --;

}

// If the two points are connected, this path only adds a ring to the graph. // This path has no effect on the connectivity and is ignored.

}

// Output the number of Route entries to be repaired

Printf ("% d \ n", total);} return 0;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.