【CF125E】MST Company

题面

https://www.luogu.org/problemnew/show/CF125E

题解

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define ri register int
#define N 200050
#define M 400050
using namespace std;
int n,m,k,cnt;
int f[N],L[M];
struct edge{int u,v,l;} e[M];
bool cmp(int x,int y){return L[x]<L[y]||(L[x]==L[y]&&(min(e[x].u,e[x].v)<min(e[y].u,e[y].v)));}
int id[N];
bool used[N];
int findroot(int x){
  if (f[x]==x) return x;
  return f[x]=findroot(f[x]);
}
bool check(int x) {
  for (ri i=1;i<=m;i++) if (e[i].u==1 || e[i].v==1) L[i]=e[i].l-x; else L[i]=e[i].l;
  for (ri i=1;i<=n;i++) f[i]=i;
  for (ri i=1;i<=m;i++) id[i]=i,used[i]=0;
  sort(id+1,id+m+1,cmp);
  int cc=0; cnt=0;
  for (ri i=1;i<=m;i++) {
    if (e[id[i]].u==1 || e[id[i]].v==1) if (cc==k) continue;
    int r1=findroot(e[id[i]].u),r2=findroot(e[id[i]].v);
    if (r1==r2) continue;
    f[r1]=r2;
    cnt++;
    used[id[i]]=1;
    if (e[id[i]].u==1 || e[id[i]].v==1) cc++;
  }
  if (cc==k) return 1; else return 0;
}
int main(){
  scanf("%d %d %d",&n,&m,&k);
  for (ri i=1;i<=m;i++) scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].l);
  int lb=-100010,rb=100010,ans=500000;
  while (lb<=rb) {
    int mid=(lb+rb)/2;
    if (check(mid)) ans=mid,rb=mid-1; else lb=mid+1;
  }
  check(ans);
  if (ans==500000 || cnt!=n-1) {
    puts("-1");
    return 0;
  }
  printf("%d\n",n-1);
  for (ri i=1;i<=m;i++) if (used[i]) printf("%d ",i);
  return 0;
}

 

posted @ 2019-07-31 12:13  HellPix  阅读(150)  评论(0编辑  收藏  举报