【POJ】1182 食物链
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【POJ】1182 食物链
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                這是《挑戰設計程序競賽》中的例題。
?
?
題目鏈接:http://poj.org/problem?id=1182
?
題意:中文題面。不贅述。
?
題解:
?
?
代碼:
?
1 //帶權并查集 2 #include<iostream> 3 #include<cstdio> 4 using namespace std; 5 const int maxn = 150010; 6 7 int f[maxn]; 8 int dep[maxn];//深度 9 10 void init(int n){ 11 for(int i = 0; i <= n ;i++){ 12 f[i] = i; 13 dep[i] = 1; 14 } 15 } 16 17 int find(int x){ 18 if(x == f[x]) 19 return x; 20 return f[x] = find(f[x]); 21 } 22 23 void join(int x,int y){ 24 x = find(x); 25 y = find(y); 26 if(x == y) return ; 27 if(dep[x] < dep[y]){ 28 f[x] = y; 29 } 30 else{ 31 f[y] = x; 32 if(dep[x] == dep[y]) 33 dep[x]++; 34 } 35 } 36 37 bool same(int x,int y){ 38 return find(x) == find(y); 39 } 40 41 int main(){ 42 int n,k; 43 int d,x,y; 44 int ans = 0; 45 scanf("%d%d",&n,&k); 46 init(n*3); 47 for(int i = 0; i < k; i++){ 48 scanf("%d%d%d",&d,&x,&y); 49 if(x <= 0 || x > n || y <= 0 || y > n || ( d == 2 && x == y)){ 50 ans++; 51 continue; 52 } 53 if(d == 1){ 54 //xy同類 55 if( same(x,y+n) || same(x,y+2*n)){ 56 ans++; 57 continue; 58 }else{ 59 join(x,y); 60 join(x+n , y+n); 61 join(x + 2*n, y + 2*n); 62 } 63 }else{ 64 //x吃y 65 if(same(x,y)||same(x,y + 2*n)){ 66 ans++; 67 continue; 68 }else{ 69 join(x,y+n); 70 join(x + n, y + 2*n); 71 join(x + 2*n,y); 72 } 73 } 74 } 75 printf("%d",ans); 76 return 0; 77 }?
轉載于:https://www.cnblogs.com/Asumi/p/9747727.html
總結
以上是生活随笔為你收集整理的【POJ】1182 食物链的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 洛谷P1527 [国家集训队] 矩阵乘法
- 下一篇: CSS中的字体描边
