题意:判断有没有同性恋的一道题,其实也可以看成是:在一颗二叉树上是否有环
思路:在并查集的基础上,有区别的一步是:当是新的两个树合并的时候,除了将一个根设为另一颗树的根的父亲外,还要加上不同性别的一层关系,我们开新的数组,vis[i]=j表示i和j是异性,还要的是将i的根的异性伙伴与j的根合并
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 1000005; const int INF = 10000000; int fa[MAXN]; int vis[MAXN]; int flag,n,m; int find(int x){ if (x != fa[x]) fa[x] = find(fa[x]); return fa[x]; } void Union(int x,int y){ int fx = find(x),fy = find(y); if (fx == fy) flag = 0; else { if (vis[fx]) fa[vis[fx]] = fy; if (vis[fy]) fa[vis[fy]] = fx; vis[fx] = fy,vis[fy] = fx; } } int main(){ int t,cas=1;; scanf("%d",&t); while (t--){ scanf("%d%d",&n,&m); flag = 1; for (int i = 0; i <= n; i++) fa[i] = i,vis[i] = 0; for (int i = 0; i < m; i++){ int a,b; scanf("%d%d",&a,&b); Union(a,b); } printf("Scenario #%d:\n",cas++); if (flag) printf("No suspicious bugs found!\n\n"); else printf("Suspicious bugs found!\n\n"); } return 0; }
HDU - 1829 A Bug's Life (并查集应用),布布扣,bubuko.com
HDU - 1829 A Bug's Life (并查集应用)
原文:http://blog.csdn.net/u011345136/article/details/23304161