您的位置:首页 > 其它

HDU1272 小希的迷宫 并查集入门||判环

2017-08-27 22:11 211 查看
题目链接:HDU1272

题目大意:需要知道如何判定无向图中存在环

假定:图顶点个数为M,边条数为E
遍历一遍,判断图分为几部分(假定为P部分,即图有 P 个连通分量)
对于每一个连通分量,如果无环则只能是树,即:边数=结点数-1
只要有一个满足      边数   >   结点数-1

原图就有环

将P个连通分量的不等式相加,就得到:
P1:E1=M1-1
P2:E2=M2-1
...
PN:EN=MN-1
    所有边数(E)
  =  所有结点数(M) - 连通分量个数(P)

即:  E + P = M  无环.否则有环 E+P>M有环 
但对于这个题目,写成 E+P=M无环 或者写成 E+P>M||E+P<M  ||circle 有环 才行。
AC代码:
/*

并查集入门
2017年8月27日22:09:57
HDU1272
AC
*/

#include <iostream>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
const int maxn=1e5+10;
int pre[maxn];
int a,b,edgenum,vnum;
bool circle;
bool vis[maxn];

void init(){
for(int i=1;i<=maxn;i++){
pre[i]=i;
vis[i]=false;
}
edgenum=vnum=0;
circle=false;
}
int find(int x){
int r=x;
while(pre[r]!=r)    r=pre[r];//查找到根节点为止
int i=x,j;
while(i!=r){
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}

void join(int x,int y){
if(x==y) circle=true;
int fx=find(x);
int fy=find(y);
if(fx!=fy){
pre[fx]=fy;
edgenum++;
}
else circle=true;
}

int main(){
while(true){
init();
scanf("%d%d",&a,&b);
//注意特判 空树也满足条件
if(a==0||b==0){
printf("Yes\n");
continue;
}
if(a==-1||b==-1) break;
vis[a]=vis[b]=true;
join(a,b);
while(true){
scanf("%d%d",&a,&b);
if(a==0&&b==0) break;
vis[a]=vis[b]=true;
join(a,b);
}
for(int i=1;i<=maxn;i++){
if(vis[i]) vnum++;
}
if(!circle&&edgenum+1==vnum) printf("Yes\n");
else printf("No\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: