HDU5631——Rikka with Graph【并查集】

来源:互联网 发布:虚拟视频软件电脑 编辑:程序博客网 时间:2024/05/21 07:57

Rikka with Graph
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1189    Accepted Submission(s): 607




Problem Description
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?

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


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


Then n+1 lines follow. Each line contains two numbers u,v , which means there is an edge between u and v.
 


Output
For each testcase, print a single number.
 


Sample Input
1
3
1 2
2 3
3 1
1 3

Sample Output
9

第一次把删掉一根和两根分开写了,不知道为啥一直错,注释掉的为错误的代码。

#include<stdio.h>const int maxn=150;int a[maxn],b[maxn],par[maxn];void init(int n){for(int i=0;i<=n;i++)par[i]=i;}int find(int x){return x==par[x]?x:find(par[x]);}void unite(int a,int b){int fa=find(a);int fb=find(b);if(fa!=fb)par[fa]=fb;}int main(){int T;scanf("%d",&T);while(T--){int n;scanf("%d",&n);for(int i=0;i<=n;i++)scanf("%d%d",&a[i],&b[i]);int sum=0;//for(int i=0;i<=n;i++)//{//int ans=0;init(n);//for(int j=0;j<=n;j++)//if(i!=j)//unite(a[j],b[j]);//for(int r=1;r<=n;r++)//{//if(par[r]==r)//ans++;//}//printf("ans=%d  ",ans);//if(ans==1)//sum++;//} for(int i=0;i<=n;i++){for(int j=i;j<=n;j++){init(n);int cnt=0;for(int k=0;k<=n;k++){if(k==i||k==j)continue;if(k!=i && k!=j)unite(a[k],b[k]);}for(int r=1; r<=n; r++){if(par[r]==r)cnt++;}if(cnt==1)sum++;}}printf("%d\n",sum);}return 0;}