POJ 1182 食物鏈(種類並查集),poj1182
題目地址:POJ 1182
一道很經典的種類並查集的題目。利用互相之間的關係來進行權值的維護。
代碼如下:
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;int bin[60000], rank[60000];int find1(int x){ int y; if(bin[x]!=x) { y=bin[x]; bin[x]=find1(bin[x]); rank[x]=(rank[x]+rank[y])%3; } return bin[x];}int main(){ int n, k, p, x, y, i, flag, f1, f2, cnt=0; scanf("%d%d",&n,&k); for(i=1;i<=n;i++) { bin[i]=i; rank[i]=0; } while(k--) { flag=0; scanf("%d%d%d",&p,&x,&y); if(x>n||y>n||(p==2&&x==y)) { cnt++; continue ; } f1=find1(x); f2=find1(y); if(p==1) { if(f1==f2) { if(rank[x]!=rank[y]) cnt++; } else { bin[f2]=f1; rank[f2]=(rank[x]+3-rank[y])%3; } } else { if(f1==f2) { if(rank[x]!=(rank[y]+1)%3) cnt++; } else { bin[f2]=f1; rank[f2]=(rank[x]+2-rank[y])%3; } } } printf("%d\n",cnt); return 0;}
北大acm題中有什題使用並查集來做的?
POJ 1611 The Suspects 最基礎的並查集
POJ 2524 Ubiquitous Religions 最基本的並查集
POJ 1182 食物鏈 並查集的拓展
注意: 只有一組資料;
要充分利用題意所給條件:有三類動物A,B,C,這三類動物的食物鏈
構成了有趣的環形。A吃B, B吃C,C吃A。也就是說:只有三個group
POJ 2492 A Bug's Life 並查集的拓展
法一:深度優先遍曆
每次遍曆記錄下該點是男還是女,只有:男-〉女,女-〉男滿足,否則,找到同性戀,結束程式。
法二:二分圖匹配
法三:並查集的拓展:和1182很像,只不過這裡就有兩組,而1182是三組,1611無限制
POJ 1861 Network == zju_1542 並查集+自訂排序+貪心求"最小產生樹"
答案不唯一,不過在ZOJ上用QSORT()和SORT()都能過,在POJ上只有SORT()才能過...
POJ 1703 Find them, Catch them 並查集的拓展
這個和POJ 2492 A Bug's Life很像,就是把代碼稍微修改了一下就AC了!
注意:And of course, at least one of them belongs to Gang Dragon, and the same for Gang Snake. 就是說只有兩個組。
POJ 2236 Wireless Network 並查集的應用
需要注意的地方:1、並查集;2、N的範圍,可以等於1001;3、從N+1行開始,第一個輸入的可以是字串。
POJ 1988 Cube Stacking 並查集很好的應用
1、與 銀河英雄傳說==NOI2002 Galaxy一樣;2、增加了一個數組behind[x],記錄戰艦x在列中的相對位置;3、詳細解題報告見銀河英雄傳說。
JOJ 1905 Freckles == POJ 2560 最小產生樹
法一:Prim演算法;法二:並查集實現Kruskar演算法求最小產生樹