【bzoj 3624】: [Apio2008]免费道路

本文深入探讨了一种使用贪心算法解决网络连接问题的方法,通过实例展示了如何在复杂网络环境中优化节点连接,确保高效稳定的数据传输。重点介绍了算法的设计思路、关键步骤及其实现细节,为读者提供了实用的解决方案。

http://www.lydsy.com/JudgeOnline/problem.php?id=3624


简单的贪心。


//#define _TEST _TEST
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
/************************************************
Code By willinglive    Blog:http://willinglive.cf
************************************************/
#define rep(i,l,r) for(int i=(l),___t=(r);i<=___t;i++)
#define per(i,r,l) for(int i=(r),___t=(l);i>=___t;i--)
#define MS(arr,x) memset(arr,x,sizeof(arr))
#define LL long long
#define INE(i,u,e) for(int i=head[u];~i;i=e[i].next)
inline const int read()
{int r=0,k=1;char c=getchar();for(;c<'0'||c>'9';c=getchar())if(c=='-')k=-1;
for(;c>='0'&&c<='9';c=getchar())r=r*10+c-'0';return k*r;}
/////////////////////////////////////////////////
const int M=100010;
int n,m,k;
int u[M],v[M];
bool sel[M];
int l,r;

int fa[20010];
/////////////////////////////////////////////////
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
inline bool unio(int x,int y)
{
	int fx=find(x),fy=find(y);
	if(fx^fy)
	{
		fa[fx]=fy;
		return 1;
	}
	return 0;
}
/////////////////////////////////////////////////
void input()
{
    n=read(); m=read(); k=read();
    l=0;r=m+1;
    rep(i,1,m)
    {
    	int _u,_v,_type;
    	_u=read(); _v=read(); _type=read();
    	if(!_type) u[--r]=_u, v[r]=_v;
    	else       u[++l]=_u, v[l]=_v;
    }
}
void solve()
{
	rep(i,1,n) fa[i]=i;
	int cnt=0;
	rep(i,1,m)
	{
		if(unio(u[i],v[i]))
		{
			if(i>=r) cnt++,sel[i]=1;
		}
	}
	if(cnt>k) {puts("no solution");return;}
	
	rep(i,1,n) fa[i]=i;
	rep(i,r,m) if(sel[i]) unio(u[i],v[i]);
	rep(i,r,m)
	{
		if(!sel[i] && cnt<k && unio(u[i],v[i]))
		{
			sel[i]=1; cnt++;
		}
		if(cnt==k) break;
	}
	if(cnt!=k) {puts("no solution");return;}
	rep(i,1,l)
	{
		if(unio(u[i],v[i])) sel[i]=1;
	}
	rep(i,1,m) if(sel[i])
	{
		printf("%d %d %d\n",u[i],v[i],i<=l);
	}
}
/////////////////////////////////////////////////
int main()
{
    #ifndef _TEST
    freopen("std.in","r",stdin); freopen("std.out","w",stdout);
    #endif
    input(),solve();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值