cheng_you_know

学而时习之!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1272

这个主要是 图的判连通 和 判不存在环 即可

#include <cstdio>  
#include <iostream>  
#include <cstring>  
#pragma comment(linker, "/STACK:102400000,102400000")  
using namespace std;  

const int MAXP = 100005;  
bool flag;  
int father[MAXP];  

void init(){  
    memset(father,-1,sizeof(father));  
    flag = true;  
}  

int find(int a){  
    if (father[a] <= 0)      return a;  
    return father[a] = find(father[a]);  
}  

void combination(int ra,int rb){  
    father[rb] = ra; //father[rb]一定为 0 或 -1  
    if ( father[ra] < 0 )  
        father[ra] = 0; // 只有-1有资格变成0  
}  

bool is_connected(){  
    int s=0;  
    for (int i =1; i < MAXP; i++)  
        if (father[i]==0)  
            s++;  
    if (s>1)return false;  
    else    return true;  
}  

int main()  
{  
    while(1){  
        int a,b,l=0;  
        init();  
        while(scanf("%d%d",&a,&b)&&a!=-1){  
            if (a<=0 && b<=0){  
                if (l==0)  
                    flag = true;  
                break;  
            }else{  
                int ra = find(a);  
                int rb = find(b);  
                if (ra == rb){ // they have same ancestor  
                    flag = false;  
                }else{  
                    combination(ra,rb);  
                }  
            }l++;  
        }  
        if (a==-1)break;  
        if (flag && is_connected()){  
            cout << "Yes" << endl;  
        }else{  
            cout << "No" << endl;  
        }  
    }  
    return 0; 
}
posted on 2013-05-30 13:55  cheng_you_know  阅读(137)  评论(0编辑  收藏  举报