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

907

被折叠的 条评论
为什么被折叠?



