B - 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(T30) T(T≤30)——The number of the testcases. 

For each testcase, the first line contains a number  n(n100) n(n≤100)

Then n+1 lines follow. Each line contains two numbers  u,v 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条边,所以枚举1条边和条边的情况;

代码:

#include <stdio.h>
#include <string.h>

const int maxn = 1e2 + 10;

int par[maxn];

struct node   //把边用结构体存下来,每个结构体对应一条边; 
{
	int st;
	int edd;
}edge[maxn];

void init(int n)
{
	for (int i = 0; i <= n; i++)
		par[i] = i;
}

int find(int x)
{
	return par[x] == x ? x : par[x] = find(par[x]);
}

void unite(int a, int b)
{
	int fa = find(a);
	int fb = find(b);
	if (fa != fb)	
		par[fa] = fb;
}

bool check(int n)    //统计是不是只有一个根节点,即使不是能全部连通 
{
	int sum = 0;
	for (int i = 1; i <= n; i++)
		if (par[i] == i)
			sum++;
	return sum == 1;
}

int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		int n;
		scanf("%d", &n);
		for (int i = 0; i < n + 1; i++)
			scanf("%d%d", &edge[i].st, &edge[i].edd);
		int sum = 0;   //sum记录可行的个数
		//题上说总共给出n + 1条边 然后我们已知n个点至少需要n - 1条边连接   数据是100左右  n^3也可以过  那就暴力枚举
		//先枚举去掉一条边是否能连通
		for (int i = 0; i < n + 1; i++)
		{
			init(n); //这一步记得 因为是枚举 每次枚举出来一条边 这个数组就要重新排列一下  回复初始状态 
			for (int j = 0; j < n + 1; j++)
			{
				if (i == j) //上面用i记录去掉的边 那么这一步就没有这条边了 所以遇到相等就跳过 
					continue;
				unite(edge[j].st, edge[j].edd); //把剩下的每个边都连接起来  
			}
			//然后在这做检查 看能不能连通所有的点 
			if (check(n))
				sum++; 
		} 
		//枚举一条边的就结束了  下面的两条边的和一条边的几乎相同  
		for (int i = 0; i < n + 1; i++)
		{
			for (int j = i + 1; j < n + 1; j++)
			{
				init(n);
				for (int k = 0; k < n + 1; k++)
				{
					if (k == i || k == j)
						continue;
					unite(edge[k].st, edge[k].edd);
				}
				if (check(n))
					sum++;
			}
		}
		printf("%d\n", sum); 
	}
	return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值