Disjoint-set notes and organize ideas

It is very basic content, and Kruskal written before, when suddenly remembered not collated.

In fact, the board wanted to save a

Disjoint-set data structure is a tree, for processing a collection of (disjoint sets only).

"Sensuous understanding" about a bunch of things is to be divided into several piles, each and everything in which only a pile in.

Concrete realization of a father, then use the array, pointing to a parent node of the element. Initial father when all the elements are its own, represents each element in their own collection. If the two elements in the same set, and their ancestors for the same.

Two main functions: join and find.

Let me talk about the find:

int find(int x) {
    if(father[x]!=x) father[x] = Find(father[x);
    return father[x];
}

Well understood, if x is his father, it is the root own collection, or to inquire layer by layer until the root node (the way the path compression - the collection points are connected directly under the root node). This function is mainly used are the same ancestor by two elements, it is determined whether the two elements in the same set.

 Then join:

void Join(int x, int y){
    int fx = Find(x), fy = join(y);
    if(fx != fy) father[fy] = fx;
    return;
}

It should imagine, if put two great collections combined, the most simple operation directly to the root node is a collection and another collection to the next. (As for the structure will be very confusing thing ...... Find the next time and then finishing on the line)

Code:

#include <bits/stdc++.h>
using namespace std;
int father[10010];
int Find(int x) {
    if(father[x]!=x) father[x]=Find(father[x]);
    return father[x];
}
void Join(int x, int y){
    int fx = Find(x), fy = join(y);
    if(fx != fy) father[fy] = fx;
    return;
}
int main() {
    for(int i=1; i<=10000; i++) father[i]=i;
    int n, m, x, y;
    scanf("%d %d", &n, &m);
    while(m--) {
        scanf("%d %d",&x,&y);
        Join(x, y);
    }
    int p;
    scanf("%d", &p);
    while(p--) {
        scanf("%d %d",&x,&y);
        if(Find(x) != Find(y)) printf("F\n");
        else printf("T\n");
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/miserweyte/p/11408458.html