poj 1703 Find them, Catch them(Dsu)
2016-02-09 12:12
393 查看
题目链接:http://poj.org/problem?id=1703
用二维数组,第一维记录元素i(f[i][0]),第二维记录与i不在同一集合的元素j(f[i][1])。
初始化f[i][0]=i,f[i][1]=0(表示没有元素);
每次操作时,合并f[a][0]和f[b][1],f[a][1]和f[b][0]。
用二维数组,第一维记录元素i(f[i][0]),第二维记录与i不在同一集合的元素j(f[i][1])。
初始化f[i][0]=i,f[i][1]=0(表示没有元素);
每次操作时,合并f[a][0]和f[b][1],f[a][1]和f[b][0]。
#include<iostream> #include<cstdio> #include<cstring> #include<math.h> #include<algorithm> using namespace std; const int INF=0x3f3f3f3f; const int maxn=100005; int T,n,m; int f[maxn][2]; void Make_Set(){ for(int i=1;i<=n;i++) f[i][0]=i,f[i][1]=0; } int find(int x){ return x==f[x][0]?x:f[x][0]=find(f[x][0]); } void Union(int a,int b){ int ra=find(a); int rb=find(b); if(ra==rb) return ; f[ra][0]=rb; } int main() { #ifndef ONLINE_JUDGE freopen("test.in","r",stdin); freopen("test.out","w",stdout); #endif scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); Make_Set(); char ch; int a,b; while(m--){ getchar(); scanf("%c%d%d",&ch,&a,&b); int tmpa=f[a][1]; int tmpb=f[b][1]; if(ch=='D'){ if(!tmpa) f[a][1]=tmpa=b; if(!tmpb) f[b][1]=tmpb=a; Union(a,tmpb),Union(tmpa,b); } if(ch=='A'){ if(find(f[a][0])==find(f[b][0])) puts("In the same gang."); else if(find(f[a][1])==find(f[b][0])) puts("In different gangs."); else puts("Not sure yet."); } } } return 0; }
相关文章推荐
- cocos2d-x Loading界面实现资源加载
- 高并发的核心技术-幂等的实现方案
- HDU 2046 骨牌铺方格(递推)
- YTU 2558: 游起来吧!超妹!
- YTU 2556: 空洞
- Android2D绘图基础
- YTU 2555: 老大的烦恼
- 基于C#的计算器(1) 带括号
- .net程序员转行做手游开发经历(四)
- YTU 2553: 谁是赢家
- cocos2d-x调用scheduleUpdate()不执行update()方法的解决办法
- Head First PHP &MySQL学习笔记
- 如何查看Dell笔记本型号?
- YTU 2552: 好好学习天天向上
- Python3之itertools模块
- 4.模型与字典的对比
- YTU 2547: Repairing a Road
- hdu--5621
- 2016年 Delphi Roadmap
- YTU 2543: 数字整除