[hdu-1272]小希的迷宫 并查集

这个懒人开始写博客了2333~

大学居然开始打acm了【高中意想不到的吧】,那,能走多远走多远吧~

题目链接:https://i.cnblogs.com/EditPosts.aspx?opt=1

大意:给出无向图,判断有没有环。给出的任意两个房间有且仅有一条路径可以相通。

分析:1.每加入两个点,放到一个集合中,如果原先在同一个集合,那再加一条边就会生成环(不只有一条路径相通),输出“No”。

坑:2.全都符合的话,还要判断有几个集合,用vis记录出现过的点。有多个集合输出“No”(集合之间没法相通)。

3.如果一组数据只有 0 0,输出“Yes”!

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 
 6 const int maxn=100005;
 7 int  f[maxn];
 8 bool vis[maxn];//判断这个数出没出现过
 9 inline int get_num(){
10     char ch;
11     bool flag=false;
12     int num=0;
13     ch=getchar();
14     while(ch<'0'||ch>'9'){if(ch=='-')flag=true;ch=getchar();}
15     while(ch<='9'&&ch>='0'){num=(num<<3)+(num<<1)+ch-'0';ch=getchar();}
16     if(flag)return -1*num;
17     else return num;
18 }
19 void init_uf(){
20     for(int i=1;i<=100000;i++)
21          f[i]=i;
22 }
23 int find(int x){
24     if(f[x]==x)return x;
25     f[x]=find(f[x]);
26     return f[x];
27 }
28 void merge_uf(int x,int y){
29     int f1=find(x),f2=find(y);
30     f[f1]=f2;
31 }
32 int main(){
33     int a,b;
34     a=get_num(),b=get_num();
35     
36     while(a>=0){
37         if(a==0&&b==0){
38             cout<<"Yes"<<endl;
39             a=get_num();b=get_num();
40             continue;//最坑的地方!如果一组数据只输入0 0,也是yes
41         }    
42         for(int i=0;i<maxn;i++)vis[i]=false;
43         bool ans=true;
44         init_uf();
45         
46         merge_uf(a,b);
47         vis[a]=true,vis[b]=true;
48         
49         a=get_num(),b=get_num();
50         int fa,fb;
51         
52         while(a!=0){
53            vis[a]=true,vis[b]=true;
54            fa=find(a),fb=find(b);
55            if(fa==fb)ans=false;
56            f[fa]=fb;
57            a=get_num(),b=get_num();
58         }
59         if(ans){
60             int ans2=0;
61             for(int i=1;i<=100000;i++)if(vis[i]&&f[i]==i)ans2++;//判断有几个集合
62             if(ans2==1)cout<<"Yes"<<endl;
63             else cout<<"No"<<endl;
64         }
65         else cout<<"No"<<endl;
66         a=get_num(),b=get_num();
67     }
68 
69     return 0;
70 }

猜你喜欢

转载自www.cnblogs.com/conver/p/10405822.html