Rikka with Graph

来源:互联网 发布:软件开发文档 编辑:程序博客网 时间:2024/05/29 15:09




                               Rikka with Graph

 

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(n100)

Then n+1 lines follow. Each line contains two numbers u,vu,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


该题的意思是给你N个顶点,N+1条边,让你随便减去几条边,还能将这些点全部连接起来的情况有多少种?

思路:因为n条边最少要n-1条边才能连接完,所以题中可以分为两种情况:一、去掉一个边有多少种情况   二、去掉两条边有 多少种情况。然后两者想加即可。

AC代码如下:

#include<cstdio>int far[110];int n;void clear(){for(int i=1;i<=n+1;i++)far[i]=i;}struct NUM{int u,v;}sum[110];int find(int x){return (far[x]==x)?x:find(far[x]); }void andd(int x,int y){int f1=find(x);int f2=find(y);if(f1!=f2)far[f1]=f2;}int main(){ int t;scanf("%d",&t);while(t--){int ans=0;scanf("%d",&n);for(int i=1;i<=n+1;i++){scanf("%d%d",&sum[i].u,&sum[i].v);}//删除一条边//for(int i=1;i<=n+1;i++){clear();for(int j=1;j<=n+1;j++){if(i!=j)//意思是去掉i这条边// andd(sum[j].u,sum[j].v);}int num=0;for(int k=1;k<=n;k++){if(k==far[k])num++;}if(num==1)ans++;}//删除两条边//for(int i=1;i<=n+1;i++){for(int j=i+1;j<=n+1;j++)//之所以从i+1开始,是因为要去掉i j这两调皮边//{clear();for(int k=1;k<=n+1;k++){if(k==i||k==j)continue;andd(sum[k].u,sum[k].v);}int num=0;for(int l=1;l<=n;l++){if(l==far[l])num++;}if(num==1)ans++;}}printf("%d\n",ans);}return 0;} 

原创粉丝点击