並查集樹數據結構hdu1325
阿新 • • 發佈:2017-06-02
ret 兩個 方式 構造 ring flag cst tree out
我的解法就是去構造了一棵樹
以數組的存儲方式
數組的值存放節點的根。
排除空樹
剩下的就是出現環和多根節點的情況
也就是排除森林和有一個節點多個入度的情況
排除森林就用到了並查集
也就是便利數組讓其僅僅有一個根
排除多個入度的情況更簡單
就是把這個點插入到數上時
假設這個點已經有了根節點,就出現了兩個入度
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; int sett[1000 + 100],g[1000 + 100]; int find2(int x) { while(x != sett[x] ) x = sett[x]; return x; } int main() { int x,y,flag=1,cases=1; while(scanf("%d%d",&x,&y)){ flag=1; for(int i=1;i<=1000;i++) sett[i]=i; // for(int i=1;i<=1000;i++) g[i]=i; memset(g,0,sizeof(g)); if(x == 0 && y == 0) flag=0; if(x < 0 && y < 0) break; else sett[y]=x; g[x]=1; g[y]=1; while(scanf("%d%d",&x,&y)){ g[x]=1; g[y]=1; if(!x&&!y) break; int fx = sett[x]; int fy = sett[y]; if( fy != y) //out circle and two roots flag=0; else sett[fy]=fx; } int countt=0; for(int i=1;i<=1000;i++) if(g[i]&&sett[i]==i) countt++; // printf("countt %d\n",countt); if(countt > 1) flag=0; // printf("flag %d\n",flag if(flag) printf("Case %d is a tree.\n",cases); else printf("Case %d is not a tree.\n",cases); cases++; // for(int i=1;i<=10;i++) // printf("%d ",i); // printf("\n"); // for(int i=1;i<=10;i++) // printf("%d ",sett[i]); // printf("\n"); } return 0; }
並查集樹數據結構hdu1325