Rikka with Graph
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1079 Accepted Submission(s): 529
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?
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.
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
题意:给你n个点,然后n+1一条边,问至少删除一条边使得图依然联通有多少种方案;
很明显,对于一个图,使得n个点联通最小需要n-1个点,所有最多删除两条边,那么就分别暴力删除一条边的情况和删除两条边的情况,这里使用并查集来查询图的连通性,每删除一条边,用并查集建图,然后查询是否只有一个父节点,如果只有一个,那么这个图就是联通的,ans++。
#include<stdio.h>
#include<algorithm>
using namespace std;
int F[200];
int n;
int a[200][2];
int findfa(int x)
{
if(x==F[x])
return x;
return x=findfa(F[x]);
}
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",&a[i][0],&a[i][1]);
for(int i=1;i<=n+1;i++)
{
for(int f=1;f<=n;f++)
F[f]=f;
for(int j=1;j<=n+1;j++)
{
if(i==j)
continue;
int x=a[j][0];
int y=a[j][1];
x=findfa(x);
y=findfa(y);
if(x!=y)
F[x]=y;
}
int flag=0;
for(int j=1;j<=n;j++)
{
int x=findfa(j);
if(x==j)
flag++;
}
if(flag==1)
ans++;
}
for(int i=1;i<=n+1;i++)
{
for(int j=i+1;j<=n+1;j++)
{
for(int f=1;f<=n;f++)
F[f]=f;
for(int k=1;k<=n+1;k++)
{
if(k==i||k==j)
continue;
int x=a[k][0];
int y=a[k][1];
x=findfa(x);
y=findfa(y);
if(x!=y)
F[x]=y;
}
int flag=0;
for(int k=1;k<=n;k++)
{
int x=findfa(k);
if(x==k)
flag++;
}
if(flag==1)
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}