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

 

The meaning of the question: Given n points and n+1 edges, ask how many ways to remove the edges, so that the whole graph is still connected after removing the edges

 

Problem solution: Use the union check set to determine whether it is connected, and then by enumerating the cases of removing one edge and removing two edges one by one, to determine whether the entire graph is connected, if so, ans++, otherwise ans remains unchanged

 

AC code:

#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++) {
        //The edges connected to a and b are directly removed to see if they can all be connected
        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 years = 0;
        //Search one by one, i = j means to take one edge, unequal means to take two edges
        //At least n-1 edges are required to connect all
        for (int i = 0; i <= n; i++) {
            for (int j = i; j <= n; j++) {
                ans += check(i, j);
            }
        }
        cout << ans << endl;
    }
    return 0;
}

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324600869&siteId=291194637