【2018/10/16测试T2】华莱士

【题目】

内网传送门
外网传送门


【分析】

60 pts:

如果把一个合法方案中的所有边定向为无向边,那么我们会发现一个合法方案对应着一 个环套树森林。同时,任何一个环套树森林一定可以对应至少一个合法方案。于是问题变为了找最小的环套树森林。

可以证明最小的边一定在某个最优方案中(证明据说和 K r u s k a l Kruskal 差不多,但我不会),所以可以像 K r u s k a l s Kruskals 算法那样从小到大加边,暴力维护环套树森林。

时间复杂度 O ( n 2 ) (n^2)

100 pts:

判断是否能加入一条边时,如果这条边的两端已经联通,我们需要知道这个联通块是否有环。 如果不连通,那么可以加入这条边,而且通过两端的联通块是否有环可以得到新的联通块是否有环。

具体就是“树+树=树,树+环套树=环套树,环之间不能合并”,因此再记录一下联通块是树还是环即可。

于是我们用并查集维护连通性,额外维护联通块里是否有环即可。

时间复杂度 O ( ( n + m ) l o g    n ) ((n+m)*log\;n)


【代码】

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 500005
using namespace std;
int type[N],father[N];
struct node
{
	int x,y,w;
	bool operator<(const node &a)  {return w<a.w;}
}a[N];
int find(int x)
{
	if(father[x]!=x)
	  father[x]=find(father[x]);
	return father[x];
}
int main()
{
//	freopen("h.in","r",stdin);
//	freopen("h.out","w",stdout);
	int n,m,i,x,y;
	scanf("%d%d",&n,&m);
	for(i=1;i<=n;++i)  father[i]=i;
	for(i=1;i<=m;++i)  scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].w);
	sort(a+1,a+m+1);
	long long tot=0,ans=0;
	for(i=1;i<=m;++i)
	{
		x=find(a[i].x);
		y=find(a[i].y);
		if(x==y&&!type[x])
		  type[x]=1,tot++,ans+=a[i].w;
		else
		{
			if(type[x]&type[y])  continue;
			father[x]=y,type[y]=type[y]|type[x];
			tot++,ans+=a[i].w;
		}
	}
	if(tot!=n)  printf("No");
	else  printf("%lld",ans);
//	fclose(stdin);
//	fclose(stdout);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/forever_dreams/article/details/83090348