Description
Input
Output
Sample Input
5 7 2
1 3 0
4 5 1
3 2 0
5 3 1
4 3 0
1 2 1
4 2 1
Sample Output
3 2 0
4 3 0
5 3 1
1 2 1
题解:
APIO的题好难想QAQ。。
我果然还是太弱了QAQ。。
写一个solve函数用于向最小生成树中添加边。
首先,优先添加1类边,再填0类边。这样就可以得出必须添加的0类边。
如果必须添加的0类边多于K条或图根本不连通,显然是无解的。
然后,把必须添加的0类边添上,再把0类边补到K条,剩下添1类边,如果0类边不够就无解,否则输出就好了。
代码如下:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#define ll long long
#define inf 0x7f7f7f7f
#define N 20005
#define M 100005
using namespace std;
int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
while(ch<='9' && ch>='0') {x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m,k,u[M],v[M],c[M],fa[N];
int top,num[2],au[N],av[N],ac[N];
bool mark[M];
int find(int x) {return fa[x]==x?x:fa[x]=find(fa[x]);}
void solve(int typ,int mx)
{
for(int i=1;i<=m;i++)
{
if(c[i]==typ && num[typ]<mx)
{
int fu=find(u[i]),fv=find(v[i]);
if(fu!=fv)
{
fa[fu]=fv;
au[++top]=u[i],av[top]=v[i],ac[top]=c[i];
mark[i]=1;num[typ]++;
}
}
}
}
int main()
{
n=read(),m=read(),k=read();
for(int i=1;i<=m;i++) u[i]=read(),v[i]=read(),c[i]=read();
top=0;
num[0]=num[1]=0;
for(int i=1;i<=n;i++) fa[i]=i;
solve(1,inf),solve(0,inf);
if(num[0]+num[1]!=n-1 || num[0]>k)
{
puts("no solution");
return 0;
}
top=0;
num[0]=num[1]=0;
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=m;i++)
{
if(c[i]==0 && mark[i])
{
int fu=find(u[i]),fv=find(v[i]);
if(fu!=fv)
{
fa[fu]=fv;
au[++top]=u[i],av[top]=v[i],ac[top]=c[i];
num[0]++;
}
}
}
solve(0,k),solve(1,inf);
if(num[0]<k)
{
puts("no solution");
return 0;
}
for(int i=1;i<=top;i++) printf("%d %d %d\n",au[i],av[i],ac[i]);
return 0;
}