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个点之间是联通的。
第一次这样用并查集…憋说话,用心感悟。
1/* ***********************************************
2Author :111qqz
3Created Time :2016年03月03日 星期四 21时11分19秒
4File Name :code/hdu/5631.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=105;
34int n;
35int f[N];
36bool ban[N];
37pi edge[N];
38
39
40void init()
41{
42 ms(f,0);
43 for ( int i = 0 ; i < N ; i++) f[i] = i;
44}
45
46int root ( int x)
47{
48 if (f[x]!=x)
49 f[x]=root(f[x]);
50 return f[x];
51}
52
53int Union( int x,int y)
54{
55 int rootx = root(x);
56 int rooty = root(y);
57 // cout<<"rootx:"<<rootx<<" rooty:"<<rooty<<endl;
58 if (rootx!=rooty)
59 {
60 f[rootx]=rooty;
61
62 return 1;
63 }
64 return 0;
65}
66
67int solve() //用并查集判断图连通性。如果是联通图,那么一定会合并(union)n-1次(得到一棵生成树)
68 //每次合并相当于添加了一条边,而且是不会使得图出现环的边。
69{
70 init(); //对于每一种情况,都要初始化一次。
71
72 int cnt_merge = 0;
73
74 for ( int i = 0 ; i <= n ; i++)
75 {
76 if (!ban[i])
77 {
78 cnt_merge+=Union(edge[i].fst,edge[i].sec);
79 }
80 }
81 return cnt_merge==n-1;
82}
83int main()
84{
85 #ifndef ONLINE_JUDGE
86 freopen("code/in.txt","r",stdin);
87 #endif
88
89 ios::sync_with_stdio(false);
90 int T;
91 cin>>T;
92 while (T--)
93 {
94 // init();
95 cin>>n;
96 for ( int i = 0 ; i <= n ; i++) cin>>edge[i].fst>>edge[i].sec;
97
98 ms(ban,false);
99
100 int ans = 0 ;
101 for ( int i = 0 ; i <= n ; i++)
102 {
103 ban[i] = true;
104 ans +=solve();
105 for ( int j = i+1 ; j <= n ; j++)
106 {
107 ban[j] = true;
108 ans +=solve();
109 ban[j] = false; //回溯
110 // cout<<"ans:"<<ans<<endl;
111 }
112 ban[i] = false ;//回溯
113
114 }
115 cout<<ans<<endl;
116 }
117
118 #ifndef ONLINE_JUDGE
119 fclose(stdin);
120 #endif
121 return 0;
122}