B - Rikka with Graph HDU - 5631 (并查集+思维)

As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them: 

Yuta has a non-direct graph with n vertices and n+1 edges. Rikka can choose some of the edges (at least one) and delete them from the graph. 

Yuta wants to know the number of the ways to choose the edges in order to make the remaining graph connected. 

It is too difficult for Rikka. Can you help her?

InputThe first line contains a number T(T30)T(T≤30)——The number of the testcases. 

For each testcase, the first line contains a number n(n100)n(n≤100). 

Then n+1 lines follow. Each line contains two numbers u,vu,v , which means there is an edge between u and v.
OutputFor each testcase, print a single number.Sample Input

1
3
1 2
2 3
3 1
1 3

Sample Output

9

题意:给出n个点,和n+1条边,问可以有多少种去掉边的方法,使去掉边后整个图仍然是连通的

题解:使用并查集来判断是否连通,再通过逐个枚举去掉一条边和去掉两条边的情况,判断整个图是否连通,如果是则ans++ 否则ans不变

AC代码:

#include<iostream>
#include<cstdio>

using namespace std;

int s[105], e[105];
int t, n;
int a, b;
int pre[105];

int Find(int r) {
    return pre[r] = pre[r] == r ? r : Find(pre[r]);
}

int check(int a, int b) {
    for (int i = 1; i <= n; i++) {
        pre[i] = i;
    }
    for (int i = 0; i <= n; i++) {
        //与a , b 相连的边直接去掉,查看是否还能够全部联通
        if (i == a || i == b)
            continue;
        int f1 = Find(s[i]), f2 = Find(e[i]);
        if (f1 != f2)
            pre[f1] = f2;
    }
    int cnt = 0;
    for (int i = 1; i <= n; i++) {
        if (pre[i] == i)
            cnt++;
        if (cnt > 1)
            return 0;
    }
    return 1;
}
int main() {
    cin >> t;
    while (t--) {
        cin >> n;
        for (int i = 0; i <= n; i++) {
            cin >> s[i] >> e[i];
        }
        int ans = 0;
        //逐个查找,i = j 代表是取一条边,不等代表是取两条边
        //要想全部联通至少需要n-1条边
        for (int i = 0; i <= n; i++) {
            for (int j = i; j <= n; j++) {
                ans += check(i, j);
            }
        }
        cout << ans << endl;
    }
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/ruruozhenhao/p/8903748.html