HDOJ 5631Rikka with Graph(图论)

来源:互联网 发布:elasticsearch5 linux 编辑:程序博客网 时间:2024/05/18 02:22

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5631


题目大意:给出一个n个点n+1条边的连通图,要求在删掉m(m>0)条边的情况下,还能保证图是连通图的方法有几种

思路:显然要保证连通图要有n-1条边,即可以删掉一条或者两条边。使用暴力枚举所有可以删除边的方法,然后对图进行dfs判断是否联通。没有使用并查集的情况下,时间为950ms接近1000ms的上限,使用并查集可以将时间缩短到300MS左右。

#include<iostream>#include<cstdio>#include<set>#include<string>#include<string.h>#include<cstring>#include<vector>#include<map>#include<queue>#include<stack>#include<cctype>#include<algorithm>#include<sstream>#include<utility>#define mt(a) memset(a,0,sizeof (a))#define fl(a,b,c) fill(a,b,c)#define SWAP(a,b,t) (t=a,a=b,b=t)#define inf 1000000000+7using namespace std;int graph[120][120];int vis[120];int x[120];int y[120];int n;int cot;void dfs(int x){    vis[x] = 1;    cot++;    for (int i = 1; i <= n; i++)    {        if (graph[x][i] && !vis[i])        {            dfs(i);        }    }}int main(){    int T;    cin >> T;    while (T--)    {        memset(graph, 0, sizeof graph);        memset(x, 0, sizeof x);        memset(y, 0, sizeof y);        scanf("%d", &n);        for (int i = 0; i < n + 1; i++)        {            scanf("%d %d", &x[i], &y[i]);            graph[x[i]][y[i]] ++;            graph[y[i]][x[i]] ++;        }        int ans = 0;        for (int i = 0; i < n + 1; i++)        {            cot = 0;            memset(vis, 0, sizeof vis);            graph[x[i]][y[i]] --;            graph[y[i]][x[i]] --;            dfs(1);            if (cot == n)            {                ans++;                for (int j = i + 1; j < n + 1; j++)                {                    memset(vis, 0, sizeof vis);                    cot = 0;                    graph[x[j]][y[j]] --;                    graph[y[j]][x[j]] --;                    dfs(1);                    if (cot == n)ans++;                    graph[x[j]][y[j]] ++;                    graph[y[j]][x[j]] ++;                }            }            graph[x[i]][y[i]] ++;            graph[y[i]][x[i]] ++;        }        printf("%d\n", ans);    }    return 0;}

0 0