"Go" and check set algorithm and path compression

Source: Internet
Author: User

And check set is my summer vacation from the master there is a trick, I think it is too subtle design. The kind of problem that I couldn't solve before could be done in such a simple and efficient way. I'm sorry for not sharing it. (Party: Damn, what's the matter with me?) Am I familiar with you? )

To see an example, Hangzhou electric 1232 unblocked project

First give you a few towns on the map, and these towns can be seen as points, and then tell you which ones are directly connected to the town. The last thing to solve is the problem of the connectivity of the whole picture. For example, give you two points, let you determine whether they are connected, or ask you the whole picture of a number of connected branches, that is, divided into several separate pieces of each other. Like the smooth works of the problem, ask still need to repair several roads, the essence is to ask for a few connected branches. If it is a 1 connected branch, it means that the points on the whole map are connected. No more road repair, if it is 2 connected branches, as long as 1 more roads, from the two branches to choose a point, to connect them together, then all the points are connected, if it is 3 connected branches, then just two more road repair ...

Use the following set of data to enter data to illustrate

4 2 1 3 4 3

The first line tells you that there are 4 points and 2 routes. The following two lines tell you that there is a road between 1, 3, 4 and 3. Then the whole picture is divided into 1-3-4 and 22-part. As long as one more road, the 2 and any other point of connection, the smooth work is achieved, then the output of this set of data is 1. Well, now programming to implement this function, the town has hundreds of, the road has not known how many, and may have a circuit. How can this be good?

I did not before Ah, since the use and search set, hey, the effect is really good! Our whole family used it!

And the set is composed of an array of integers and two functions. Array pre[] Records what the leading point of each point is, and the function find is the lookup, and the join is a merge.

int pre[1000];

int find (int x) Find root node

{

int r=x;

while (Pre[r]! = r)// returns the root node R

R=pre[r];

int I=x, J;

while (i! = r)//< c2> Path Compression

{

j = pre[I]; Use the TEMP variable J to record his value before changing the superior.

pre[i]= R; Change the parent to the root node

I=j;

}

return R;

}

void join (int x,int y)                                                                                                          //determine if x y is connected,

If already connected, do not have to tube//if not connected, they are located in the connected branch of the merger,

{

int Fx=find (x), Fy=find (y);

if (fx!=fy)

Pre[fx]=fy;

}

To explain and look at the principles of the set, I will cite a more loving example. There are a variety of heroes scattered in the river, there are thousands of many. They do not have any legitimate occupation, carrying a sword all day walking around, encounter and oneself is not a person, it is unavoidable to fight a. But the heroes have a good point is to talk about loyalty, definitely do not beat their friends. And they believe that "friend of Friends is my friend", as long as it can be connected through a friend relationship, no matter how many bends, are considered to be one of our own. In this way, the lake has formed a community, through the friendship between the 22 series together. The people who are not in the same community, however, cannot be connected by friends, so they can be assured of death. But two of people who don't know each other, how to tell if they belong to a circle of friends?

We can nominate a more prestigious person in every circle of friends, as the representative of the circle, so that each circles can name "Zidane's friends Team" and "Ronaldo Friends team" ... Two people as long as each other to their own captain is not the same person, you can determine the foe relationship.

But there are questions Ah, heroes only know their direct friend is who, many people do not know the captain, to judge their captain is who, can only aimlessly through friends friend Relations asked: "You are not the captain?" Aren't you the captain? "In this way, the captain's face is Shing, and the efficiency is too low, and the possibility of falling into an infinite cycle." So the captain ordered and re-teamed. All the people in the team to implement a hierarchical system, the formation of a tree structure, my captain is the root node, the following are two level players, three level players. Everyone can just remember who their superiors are. When the judgment foe, as long as a layer of upward ask, until the highest level, you can determine in a short time who is the captain. Since all we care about is whether two people are connected, how they are connected, and what the structure is inside each circle, or even who the captain is, it doesn't matter. So we can let the captain arbitrarily re-team, as long as not the wrong foe relationship is good. So, the door-pie arose.

Let's take a look at the implementation of the set. int pre[1000]; This array, which records each warrior's superior is who. Heroes from 1 or 0 start numbering (according to test instructions), pre[15]=3 that the 15th Warrior's superior is the number 3rd warrior. If a person's superior is himself, that means he is the boss, look for the end. There is also a loner, such as Ouyang Fung, then his superiors are himself. Everyone only recognized their superiors. For example, Hu Qing cattle students only know their superiors are yang left to make. Who is Zhang Mowgli? Don't know! If you want to know who your masters are, you can only check them on a level. Find this function is to find the use of the Masters, the meaning of the more clear (path compression algorithm regardless of, later).

int find (int x)//Find the Masters of my (x)

{

int r=x; Entrust R to find the Masters.

while (Pre[r]!=r)//If the Superior of R is not R himself (that is to say, he is not the master of the hero = =)

R=PRE[R]; R went on to find his superiors until he found the boss.

return R; The Masters of the arrivals ~ ~

}

Look again at the Join function, which is to connect a line between two points, so that all the points of the two plates they are in are interoperable. This is very good on the map, draw a line on the line. But we are now using and looking at the situation in the martial arts, there is only one pre[] array, how to achieve it? Or the case of the river, assuming the current situation in the martial arts. Virtual Bamboo Small Monk and Zhou Zhijo mm is I very much like the two characters, their ultimate boss is the Xuan Tzu Abbot and extermination division too, it is obviously two camps. I do not want them to fight each other, they said to them: "You two cheerleaders, good friends." "They look at my face and agree." This consent can be a serious matter, the whole Shaolin and Emei faction people can not fight. How can you make such a big change, and how many places to change? Actually very simple, I said to the Xuan Tzu Abbot: "Master, trouble you to change your superiors to extinction division too." In this way, the two original all the staff of the ultimate boss is a teacher too, that still play a ball ah! Anyway, all we care about is connectivity, the internal structure of the portal doesn't matter. "Xuan Yi listens to certainly the fire is big:" I rely on what I become her staff, how not in turn? I protested! "The protests were ineffective, the heavens arranged, the greatest. Anyway who joins who the effect is the same, I have a handy designation. The meaning of this function is very clear, right?

void join (int x,int y)//I want to make a friend of bamboo and Zhou Zhijo

{

int Fx=find (x), Fy=find (y); Empty Bamboo's eldest brother is Hyun-tzu, zhi if mm's eldest brother is extinct

    if (fx!=fy)                                                                                    //Xuan Keats extinction apparently not the same person

Pre[fx]=fy; The abbot had to be wronged and bent to become a teacher too.

}

Then take a look at the path compression algorithm. The process of building a portal is connected with the Join function two people two people, who when who's men are completely random. The final tree structure will become what kind of lip, I can not predict, Higo is also possible. This will make the search less efficient. The ideal situation is that all the direct superiors are masters, a total of two-level structure, as long as the search to find the leader. If you can't do it all, it's best to approach it as close as possible. This results in a path compression algorithm. Imagine a scene like this: Two heroes who don't know each other meet and wonder if they can beat them. So hurriedly called to ask their superiors: "You are not the Boss?" "The superior said:" I am not ah, my superior is who who, you ask him to see. "All the way down, the original two of the final boss are East factory Cao father-in-law." "Ah Ah, the original is to remember their own people, Western ceremony, in the next three camps six groups of white flour gourd baby!" "Nice to meet you, in the next nine Battalion 18 Group of Fairy Dog tail flowers!" "The two men happily drank in hand." "And so on, and so on, two students please wait, there are things not finished!" "I call them both." "Oh, yes, but also to do path compression." The two were disillusioned. White gourd Baby Call his superior six leader: "Team leader Ah, I checked, its Xi's Masters is Cao father-in-law." Why don't we join and Cao Gong under the bar, save the level is too low, later find the Boss Hemp ring. "Well, that makes sense." "The white gourd doll then calls to the three battalion commander who just visited ... The Fairy Dog Tail flower also did the same thing. In this way, all the characters involved in the query are gathered under the direct leadership of Cao's father-in-law. Each query is optimized, so the number of layers in the entire gate tree is maintained at a relatively low level. Path compression code, can understand very well, do not understand also do not matter, directly copied on the line. In short, the function that it implements is this meaning.

"Go" and check set algorithm and path compression

Related Article

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.