1. 程式人生 > >帶權並查集求最環

帶權並查集求最環

/*

把每個同學看成一個點,資訊的傳遞就是在他們之間連有向邊,遊戲輪數就是求最小環。

圖論求最小環,我在裡面看到了並查集。

假如說資訊由A傳遞給B,那麼就連一條由A指向B的邊,同時更新A的父節點,A到它的父節點的路徑長也就是B到它的父節點的路徑長+1。

這樣我們就建立好了一個圖,之後資訊傳遞的所有環節都按照這些路徑。遊戲結束的輪數,也就是這個圖裡最小環的長度。

如果有兩個點祖先節點相同,那麼就可以構成一個環,長度為兩個點到祖先節點長度之和+1。

*/

#include <stdio.h>
#include <iostream>
#include <math.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <queue>
#include <stack>
#include <iomanip>
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef pair<int,int> pii;
typedef long long ll;
typedef unsigned long long ull;
typedef double ld;
typedef long double lld;
typedef vector<int> vi;
#define lowbit(x) (x&-x)
#define fi first
#define se second
#define fin freopen("1.txt","r",stdin);
#define fout freopen("1.txt","w",stdout);
ll mod = 1000000007;
const int maxn = 1000000;


inline int Read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

int n, m;

int father[maxn + 5];
int dis[maxn + 5];
int ans;
int fa(int x) {
    if(father[x] != x) {
        int last = father[x];
        father[x] = fa(father[x]);
        dis[x] += dis[last];
    } 
    return father[x];
}

void check(int a, int b) {
    int x = fa(a);
    int y = fa(b);
    if(x != y) {
        father[x] = y;
        dis[a] = dis[b] + 1;
    } else {
        ans = min(ans, dis[a] + dis[b] + 1);
    }
}
                                 
int main() {
    scanf("%d", &n);
    ans = n;
    for(int i = 1; i <= n; i++) {
        father[i] = i;
    }
    int x;
    int u, v;
    for(int i = 1; i <= n; i++) {
        scanf("%d%d", &u, &v);
        check(u, v);
    }
    printf("%d\n", ans);
    return 0;
}