码迷,mamicode.com
首页 > 其他好文 > 详细

File Transfer (25)

时间:2015-06-08 08:22:15      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

这是一道考察“并查集”的题目

并查集只有并和查这两种操作

值得注意的是,因为查的操作是O(height)的,所以我们可以依靠一些小技巧降低树的高度,并且不增加时间复杂度

#include <iostream>
using namespace std;
bool check(int x, int y);
void connect(int x, int y);
int father(int x);

int *a;
int main()
{
    int n;    cin >> n;
    a = (int *)malloc((n + 1)*sizeof(int));
    for (int i = 1; i <= n; i++){
        a[i] = i;
    }

    char get;
    int x, y;
    while ( cin>>get , get != S){
        if (get == C){
            cin >> x >> y;
            if (check(x, y) == true){
                cout << "yes" << endl;
            }
            else{
                cout << "no" << endl;
            }
        }
        else if (get == I){
            cin >> x >> y;
            connect(x, y);
        }
    }

    int count = 0;
    for (int i = 1; i <= n; i++){
        if (a[i] == i){
            count++;
        }
    }
    if (count == 1){
        cout << "The network is connected." << endl;
    }
    else{
        cout << "There are " << count << " components." <<endl;
    }


    cin >> n;
}
bool check(int x, int y)
{
    if (father(x) == father(y)){
        return true;
    }
    else{
        return false;
    }
}
void connect(int x, int y)
{
    int fx = father(x), fy = father(y);
    if (fx != fy){
        a[fy] = fx;
    }
    return;
}
int father(int x)
{
    if (a[x] == x){
        return x;
    }
    return a[x] = father(a[x]);  //这就是巧妙的地方,如果x在树中很深,这种操作使其直接连接到父亲节点上,节省了很多时间
}

 

File Transfer (25)

标签:

原文地址:http://www.cnblogs.com/zhouyiji/p/4560014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!