九度OJ——1109连通图

来源:互联网 发布:剑网三花萝捏脸数据 编辑:程序博客网 时间:2024/05/22 15:41

题目描述:
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
输入:
每组数据的第一行是两个整数 n 和 m(0<=n<=1000)。n 表示图的顶点数目,m 表示图中边的数目。如果 n 为 0 表示输入结束。随后有 m 行数据,每行有两个值 x 和 y(x<=n)(y <=n),表示顶点 x 和 y 相连,顶点的编号从 1 开始计算。输入不保证这些边是否重复。
输出:
对于每组输入数据,如果所有顶点都是连通的,输出”YES”,否则输出”NO”。
样例输入:
4 3
1 2
2 3
3 2
3 2
1 2
2 3
0 0
样例输出:
NO
YES


思路:
利用并查集判断图的顶点是否属于一个集合。
AC代码:

#include <iostream>using namespace std;const int MAX = 1001;class UF{    private:        int data[MAX];        int count;    public:        //构造函数        UF(int N){            this->count = N;            for(int i = 0 ; i < MAX ; i++){                this->data[i] = -1;            }        }        //查找操作        int Find(int root){            if(this->data[root] < 0){                return root;            }else{                return this->data[root] = this->Find(this->data[root]);            }        }        //并操作        void Union(int root1,int root2){            root1 = this->Find(root1);            root2 = this->Find(root2);            if(root1 == root2){                return;            }else if(root1 < root2){                this->data[root1] += this->data[root2];                this->data[root2] = root1;                this->count--;            }else{                this->data[root2] += this->data[root1];                this->data[root1] = root2;                this->count--;            }        }        //判断是否全部连通        bool isConnected(){            return this->count == 1;        } };int N,M;int main(){    while(cin>>N>>M){        if(N == 0){            break;        }        UF uf(N);        for(int i = 0 ; i < M ; i++){            int root1,root2;            cin>>root1>>root2;            uf.Union(root1,root2);        }        if(uf.isConnected()){            cout<<"YES"<<endl;        }else{            cout<<"NO"<<endl;        }    }    return 0;}
原创粉丝点击