杭电-5631 Rikka with Graph (并查集应用)

来源:互联网 发布:vs 打开报表数据 编辑:程序博客网 时间:2024/05/07 02:41

Rikka with Graph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1001    Accepted Submission(s): 470


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(T30)——The number of the testcases.
For each testcase, the first line contains a number n(n100).
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
131 22 33 11 3
 
Sample Output
9
Source
BestCoder Round #73 (div.2)
Recommend
hujie   |   We have carefully selected several similar problems for you:  5780 5779 5778 5777 5776 

解题思路:
这道题给了n个点,n+1条边,问存在多少个方案使图去掉1条或2条边后,仍能连通;
(PS:n个点至少要有n-1条边才能连通)
AC代码:
#include<cstdio>#include<cstring>int u[110],v[110],n;bool use[110];int set[110];int find(int x){while(x!=set[x]){x=set[x];}return x;}void hebing(int a,int b){int fa=find(a);int fb=find(b);if(fa!=fb)set[fa]=fb;}bool judge()         //判断是否连通 {int i;for(i=1;i<=n;++i)set[i]=i;for(i=0;i<=n;++i){if(use[i])hebing(u[i],v[i]);}int cnt=0;bool sign=true;for(i=1;i<=n;++i){if(set[i]==i)cnt++;if(cnt>1){sign=false;break;}}return sign;}int main(){int i,j,t;scanf("%d",&t);while(t--){scanf("%d",&n);for(i=0;i<=n;++i){scanf("%d%d",&u[i],&v[i]);use[i]=true;}int ans=0;for(i=0;i<=n;++i){use[i]=false;if(judge())//删去一条边 ans++;for(j=i+1;j<=n;++j){use[j]=false;if(judge())//删去两条边 ans++;use[j]=true;  //还原}use[i]=true;    //还原}printf("%d\n",ans);}return 0;}


0 0