首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >小希的迷宫-HDU-1272(并查集 or 树性质)

小希的迷宫-HDU-1272(并查集 or 树性质)

作者头像
Cell
发布2022-02-25 14:49:17
发布2022-02-25 14:49:17
2810
举报
文章被收录于专栏:Cell的前端专栏Cell的前端专栏

题目链接:小希的迷宫

并查集:

  • 无回路
  • 单连通

并查集做,首先想到的是判断两个点是否连通,不连通就合并,已连通的话说明会形成回路,则可以判定 No,交了一发错了。 想了一下没有考虑到多个连通域的情况,该题必须只有一个连通域

树的性质:

既然单连通无回路,则这肯定是一棵树;那么 edge=v-1;

最后注意空树的情况,至于自环我这里 No 也过了,没有去验证自环 Yes 的情况了

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

//并查集 #include<bits/stdc++.h> using namespace std; int pre[100001]; int find(int root){ int son,t; son=root; while(root!=pre[root]) root=pre[root]; while(son!=root){ t=pre[son]; pre[son]=root; son=t; } return root; } void join(int a,int b){ int x=find(a),y=find(b); if(x!=y) pre[y]=x; } int main(){ int a,b,flag,i,sum; while(1) { flag = 0; while(~scanf("%d%d",&a,&b) && a!=0 && b!=0){ if(a==-1 && b==-1) return 0; if(pre[a]==0)pre[a]=a; if(pre[b]==0)pre[b]=b; if(find(a)==find(b))flag = 1; else if(flag!=1) join(a,b); } for(sum = 0,i=1;i<100001;i++){ if(pre[i]==i)sum++; pre[i] = 0; } if(sum>1 || flag == 1) printf("No\n"); else printf("Yes\n"); } } //1 2 3 4 0 0 No 没有连通 //0 0 Yes //1 1 0 0 No(该代码)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

//树性质 #include <stdio.h> bool s[100001]; int main() { int a,b,i,len,num,v; for(i=0;i<100001;++i) s[i]=false; len=0,num=0,v=0; while(1) { scanf("%d%d",&a,&b); if(a==-1&&b==-1) break; if(a==0&&b==0) { if(v==0) { printf("Yes\n"); continue; } if(num==len-1) //划重点!! printf("Yes\n"); else printf("No\n"); num=len=v=0; for(i=0;i<100001;++i) s[i]=false; continue; } v=1; if(s[a]==false) len++;//点数 if(s[b]==false) len++; s[a]=s[b]=true; num++;//边数 } return 0;

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-08-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目链接:小希的迷宫
  • 并查集:
  • 树的性质:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档