BestCoder Round #73 (div.2) Rikka with Graph 1002

本文介绍了一个关于图论的问题“RikkawithGraph”,该问题要求在给定的非定向图中删除部分边以确保剩余的图保持连通,并计算所有可能的删除方案数量。文章提供了一种通过并查集实现的解决方案,该方法涉及暴力删除一条或两条边,时间复杂度为O(N^3)。

Rikka with Graph

 
 Accepts: 123
 
 Submissions: 525
 Time Limit: 2000/1000 MS (Java/Others)
 
 Memory Limit: 65536/65536 K (Java/Others)
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?

Input

The first line contains a number T(T \leq 30)T(T30)——The number of the testcases.

For each testcase, the first line contains a number n(n \leq 100)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
1
3
1 2
2 3
3 1
1 3
Sample Output
9

并查集。

暴力删除一条或者两条边。O(N^3)



// Yu 20160221
//bestcoder Rikka with Graph
#include<iostream>
//#include<stdlib.h>
//#include<string.h>
using namespace std;


#define MAX_N 103
int set[MAX_N];
pair<int,int> p[MAX_N];


int find(int x)
{
	int r=x;
	while(set[r]!=r)
		r=set[r];
	return r;
}

int merge(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx==fy)	return 0;
	else
		set[fx]=fy;
	return 1;	
}



int main()
{
	int T;
	int n;
	long count,num;
	
	cin>>T;
	while(T--)
	{
		num=0;
		cin>>n;
		for(int i=0;i<=n;i++)
		{
			cin>>p[i].first>>p[i].second;
		}
		
		for(int i=0;i<=n;i++)
		{
			for(int j=i;j<=n;j++)
			{
				count=n;
				for(int l=0;l<=n;l++)
				{
					set[l]=l;
				}
				for(int k=0;k<=n;k++)
				{
					if(k!=i&&k!=j)
					{
						if(merge(p[k].first,p[k].second)==1)
							count--;
					}
				}
				
				if(count==1)
					num++;
			}
		}
		cout<<num<<endl;	
	}	
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值