1. 程式人生 > 其它 >食物鏈【並查集】

食物鏈【並查集】

技術標籤:並查集

食物鏈(並查集維護點到根結點的距離)

題目

具體程式碼如下

#include<iostream>

using namespace std;

const int N = 50010;

int n, k;
int p[N], d[N];

int find(int x){
    if(p[x] != x){
        int t = find(p[x]);
        d[x] += d[p[x]];
        p[x] = t;
    }
    return p[x];
}

int main(){
    
    scanf("%d%d"
, &n, &k); for(int i=1; i<=n; ++i) p[i] = i; int res = 0; while(k--){ int t, x, y; scanf("%d%d%d", &t, &x, &y); if(x > n || y > n) {res++; continue;} int px = find(x), py = find(y); if
(t == 1){ if(px == py && (d[x] - d[y]) % 3) res++;//不能寫成d[x]%3 == d[y]%3因為中間有減法操作可能產生負數 else if(px != py){ p[px] = py; d[px] = d[y] - d[x];//x和y同類根結點為py,px到py距離為?所以(d[x] + ? - d[y])% 3 == 0, ? = d[y] - d[x] } }else{ if
(px == py && (d[x] - 1 - d[y]) % 3) res++; else if(px != py){ p[px] = py; d[px] = d[y] + 1 - d[x]; //同上面推導一樣 } } } printf("%d\n", res); return 0; }