bc #73 B || hdu 5631 Rikka with Graph (并查集判断无向图的连通性)

http://acm.hdu.edu.cn/showproblem.php?pid=5631 题意;给出一张n个点n+1(n<=100)条边的无向图,现在删除若干条边(至少一条边),问删完之后图依然联通的方案数。 思路:分析可知,由于只删边,不删点,n个点,最少需要n-1条边才能联通,所以最多删两条边。我们可以暴力枚举删除的两条边(或者一条边) O(n^2)的复杂度完全可以接受。剩下的问题就变成了每次删边之后判断图的连通性。 题解给出的是bfs。。。大概是bfs一遍,然后入队的点数是n就联通? 或者dfs一遍也可以? 也是标记过的点数是n就说明联通? 但是看到排名考前的人都是用到了并查集来判断...比较巧妙。

具体做法是:先把所有的点孤立出来,然后开始添加边,每次union成功(就是添加了一条边)的时候计数器+1,n个点如果能合并n-1次,也就是添加了n-1条有效边(最多也只可能是n-1条,那么说明这n个点之间是联通的。

第一次这样用并查集...憋说话,用心感悟。

/* ***********************************************
Author :111qqz
Created Time :2016年03月03日 星期四 21时11分19秒
File Name :code/hdu/5631.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6const int N=105;
 7int n;
 8int f[N];
 9bool ban[N];
10pi edge[N];
1void init()
2{
3    ms(f,0);
4    for ( int i = 0 ; i < N ; i++) f[i] =  i;
5}
1int root ( int x)
2{
3    if (f[x]!=x)
4    f[x]=root(f[x]);
5    return f[x];
6}
1int Union( int x,int y)
2{
3    int rootx = root(x);
4    int rooty = root(y);
5  //  cout<<"rootx:"<<rootx<<" rooty:"<<rooty<<endl;
6    if (rootx!=rooty)
7    {
8    f[rootx]=rooty;
1    return 1;
2    }
3    return 0;
4}
1int solve()       //用并查集判断图连通性。如果是联通图,那么一定会合并(union)n-1次(得到一棵生成树)      
2    //每次合并相当于添加了一条边,而且是不会使得图出现环的边。
3{
4    init();  //对于每一种情况,都要初始化一次。
    int cnt_merge = 0;
 1    for ( int i = 0 ; i <= n ; i++)
 2    {
 3    if (!ban[i])
 4    {
 5        cnt_merge+=Union(edge[i].fst,edge[i].sec);
 6    }
 7    }
 8    return cnt_merge==n-1;
 9}
10int main()
11{
12    #ifndef  ONLINE_JUDGE 
13    freopen("code/in.txt","r",stdin);
14  #endif
1    ios::sync_with_stdio(false);
2    int T;
3    cin>>T;          
4    while (T--)
5    {
6      //  init();
7        cin>>n;
8        for ( int i = 0 ; i <= n ; i++) cin>>edge[i].fst>>edge[i].sec;
        ms(ban,false);
 1        int ans = 0  ;
 2        for ( int i = 0 ; i <= n ; i++)
 3        {
 4        ban[i] = true;
 5        ans +=solve();
 6        for ( int j = i+1 ; j <= n ; j++)
 7        {
 8            ban[j] = true;
 9            ans +=solve();
10            ban[j] = false; //回溯
11        //    cout<<"ans:"<<ans<<endl;
12        }
13        ban[i] = false ;//回溯
1        }
2        cout<<ans<<endl;
3    }
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}