HDU 5631 Rikka with Graph 暴力 并查集

Rikka with Graph

题目连接:

http://acm.hdu.edu.cn/showproblem.php?pid=5631

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

Hint

题意

众所周知,萌萌哒六花不擅长数学,所以勇太给了她一些数学问题做练习,其中有一道是这样的:

给出一张 n 个点 n+1 条边的无向图,你可以选择一些边(至少一条)删除。

现在勇太想知道有多少种方案使得删除之后图依然联通。

当然,这个问题对于萌萌哒六花来说实在是太难了,你可以帮帮她吗?

题解:

n个点,n+1条边,显然你最多就只能删除两个点让他成为一棵树

所以我们就直接暴力枚举两个点就好了,然后我们再用并查集去check一下

代码

#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
const int maxn = 150;
int fa[maxn];
int fi(int u){
return u != fa[u] ? fa[u] = fi( fa[u] ) : u;
} void uni(int u ,int v){
int p1 = fi( u ) , p2 = fi( v );
if( p1 != p2 ) fa[p1] = p2;
}
int v[maxn],u[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;scanf("%d",&n);
int E = n+1;
for(int i=1;i<=E;i++)
scanf("%d%d",&v[i],&u[i]);
int ans = 0;
for(int i=1;i<=E;i++)
{
for(int j=1;j<=n;j++)
fa[j]=j;
for(int j=1;j<=E;j++)
{
if(i==j)continue;
uni(v[j],u[j]);
}
int flag = 1;
for(int j=1;j<=n;j++)
if(fi(fa[j])!=fi(fa[1]))
flag = 0;
if(flag)ans++;
}
for(int i=1;i<=E;i++)
{
for(int j=i+1;j<=E;j++)
{
if(i==j)continue;
for(int k=1;k<=n;k++)
fa[k]=k;
for(int k=1;k<=E;k++)
{
if(k==i)continue;
if(k==j)continue;
uni(v[k],u[k]);
}
int flag = 1;
for(int k=1;k<=n;k++)
if(fi(fa[k])!=fi(fa[1]))
flag = 0;
if(flag)ans++;
}
}
cout<<ans<<endl;
}
}
上一篇:HDU 6090 Rikka with Graph


下一篇:2017ACM暑期多校联合训练 - Team 5 1006 HDU 5205 Rikka with Graph (找规律)