hdu1272&&poj1308 普通并查集+判断集合个数
思路如题。
但坑点是:
#会出现0,0这样单组的数据,并且要求你输出yes----这个没有那位兄弟的提醒我是想不到的
#题目看似要求你判断是否为树,实际上除了flag==0以外,还得联通。
第一次wa在0,0,第二次wa在没有判断联通。第三次wa在处理第一次的wa时,用了一个continue,下面的ok就没有++;
#include <iostream> #include <math.h> #include <string.h> #include <vector> #include <map> #include <queue> #include <stdio.h> #include <algorithm> #include <cstdio> using namespace std; const int maxn=1e6+5; int flag=0,cnt=0,vis[maxn],fa[maxn]; int find(int x) { if(fa[x]!=x) { fa[x]=find(fa[x]); } return fa[x]; } void unit(int x,int y) { int f1=find(x),f2=find(y); if(f1==f2) { flag=1; return; } else { fa[f2]=f1; } } void pre( ) { for(int i=1;i<=maxn;i++) { vis[i]=0; fa[i]=i; } flag=0; cnt=0; } int main() { freopen("lys.in","r",stdin); int a,b,ok=1; pre(); while(ok) { cin>>a>>b; if(a==-1) { ok=0;break; } if(a!=0) { cnt++; unit(a,b); vis[a]=1; vis[b]=1; } else if(a==0) { if(cnt==0) { printf("Case %d is a tree.\n",ok); ok++; continue; } if(flag==1) { printf("Case %d is not a tree.\n",ok); } else { int f=0; for(int i=1;i<=maxn;i++) { if(vis[i]==0) { continue; } if(f==0) { f=find(i); } else { if(f!=find(i)) { flag=1; } } } if(flag==1) { printf("Case %d is not a tree.\n",ok); } else { printf("Case %d is a tree.\n",ok); } } pre( ); ok++; } } }
分类:
图论
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)