Zju 1268 Is It A Tree?解题分析(附:HDOJ 1325 并查集参考代码)

来源:互联网 发布:linux cp断点续传 编辑:程序博客网 时间:2024/05/16 17:01

http://acm.zju.edu.cn/show_problem.php?pid=1268

http://acm.hdu.edu.cn/showproblem.php?pid=1325

判断是否是一颗有向树。注意没有分支(简称为边)也是树(空树)。非空树的判断条件是

(1)结点数要等于边数+1;

(2)无环;

(3)结点连通;

(4)无任何结点有多于1个的父结点。

定义整型数组parents存放父结点(初值1~N),cntNodes存放(子)树结点数。并操作时并到起点的根上。那么上面(2)的判断可以用查操作搞定(输入一条边<a,b>时,若a、b的根相同则有环);(1)和(3)的判断其实只要判断(1),可以在并查集做完后通过扫描parents数组进行,也可以在并操作时统计边数和结点数然后再判断;(4)可以在输入一条边<a,b>时判断parents[b]!=b,是则结点b有多于1个的父结点。注意以下几个测试:

0 0  //is a tree

1 1 0 0 //is not a tree

1 3 2 3 0 0 //is not a tree

1 2 2 3 1 3 0 0 //is not a tree


使用并查集求解HDOJ 1325的参考代码如下:

#include <iostream>#include <algorithm>using namespace std;const int N=100001;int parents[N], cntNodes[N];//后一个数组存放各个集合的结点总数int edges, nodes;void init(){    for(int i=1;i<N;i++)    {        parents[i]=i;        cntNodes[i]=1;    }    edges=0;    nodes=0;}int findSet(int i){    int root=i;    while(root != parents[root])    {        root=parents[root];    }    int k=i;    while(k != root)//路径压缩,为了提高效率;不考虑效率可以不要这段代码    {        int t=parents[k];        parents[k]=root;        k=t;    }    return root;}bool unionSet(int a, int b){    int pa=findSet(a);    int pb=findSet(b);    if(pa==pb) return false;    edges++;    parents[pb]=pa;    nodes=cntNodes[pa]+=cntNodes[pb];    return true;}bool run(int now){    init();        bool flag=true;    while(true)    {        int a,b;               cin>>a>>b;        if (a<0 && b<0) return false;                if (a==0 && b==0) break;        if (flag==false) continue;        if (parents[b]!=b) flag=false;                if (unionSet(a,b)==false) flag=false;    }    cout << "Case "<<now;    if (flag==true && (edges==0 && nodes==0 || edges==nodes-1))        cout << " is a tree."<<endl;    else        cout << " is not a tree."<<endl;    return true;}int main(){#ifndef ONLINE_JUDGE    freopen("e:\\input.txt", "rt", stdin);#endif    int now=1;    while(run(now++));    return 0;}


原创粉丝点击