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)T(T≤30)——The number of the testcases.
For each testcase, the first line contains a number n(n≤100)n(n≤100).
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
1
3
1 2
2 3
3 1
1 3
Sample Output
9
题目大意:给你n个点,n+1 条路,让你去掉一些路仍能保持所有路是贯通的。(即只有一个根节点),求有多少种去掉路的情况。
思路:n个点,所以至少要有n-1条路才能保持所有的路贯通。所以便有去掉一条路和去掉两条路的情况。分开来讨论,每种情况下循环判断是否只有一个根节点,用ans++来统计所有的情况。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int pre[11000];
bool t[11000];
int ans,n;
struct node
{
int u,v;
}p[111];
void init()
{
for(int i=1;i<=n;i++)
{
pre[i]=i;
}
}
int find(int x)//这个find函数虽然可以用while()写,但是有些题目会超时,所以还是建议用递归来写
{
if(pre[x]==x)
return x;
return pre[x]=find(pre[x]);
}//将根节点存入
void mix(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
pre[fy]=fx;
}
}
int main()
{
int s;
cin>>s;
while(s--)
{
ans=0;
int u,v,i,j,k,l;
cin>>n;
for(int i=1;i<=n+1;i++)
{
scanf("%d%d",&p[i].u,&p[i].v);
}
//开始查去掉一条边的情况
for(i=1;i<=n+1;i++)
{
init();
for(j=1;j<=n+1;j++)
{
if(j==i)
{
continue;
}
//int flag=0;
mix(p[j].u,p[j].v);
}
int flag=0; //判断是否只有一个根节点
for(k=1; k<=n; k++)
{
if (pre[k]==k)
flag++;
}
if (flag==1)
ans++;
}
// printf("%d!!! !!!\n",ans);//调试的时候用这一步可以检查去一条边的情况是否写对了。
//开始查去两条边的情况
for(i=1;i<=n+1;i++)
{
for(j=i+1;j<=n+1;j++)
{
init();
for(k=1;k<=n+1;k++)
{
if (i==k||j==k)
{
continue;
}
mix(p[k].u,p[k].v);
}
int flag=0; //判断是否只有一个根节点
for(l=1; l<=n; l++)
{
if (pre[l]==l)
flag++;
}
if (flag==1)
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}