csu 1541: There is No Alternative(Kruskal 最小生成树)

#include<cstdio>

#include<cstring>

#include<iostream>

#include<algorithm>

using namespace std;

const int MAXN=1000000+5;

struct road

{

  int f,t;

  int w;

};

road vil[MAXN];

int fa[1000+5];

int target[MAXN];

int n,m;

int mark,coun;

int cmp(road a,road b)

{

  return a.w<b.w;

}

int findfa(int x)

{

  return fa[x]==x?x:fa[x]=findfa(fa[x]);

}

int kruskal(int flag)

{

  int res=0;

  for(int i=1;i<=n;i++) fa[i]=i;//!!!!!!!这里错了,应该是对村庄一开始是以自己为根不是路!

  for(int i=0;i<m;i++)

  {

    if(i==flag) continue;

    int x=findfa(vil[i].f);

    int y=findfa(vil[i].t);

    if(x!=y)

    {

      if(mark==0)

      {

        target[coun++]=i;

      }

      fa[x]=y;

      res+=vil[i].w;

    }

  }

  return res;



}

int main()

{

  int i,j,k;

  int cnt,worth,temp;

    scanf("%d%d",&n,&m);

    cnt=0;

    worth=0;

    mark=0;

    coun=0;

    for(i=0;i<m;i++)

    {

      scanf("%d%d%d",&vil[i].f,&vil[i].t,&vil[i].w);

    }

    sort(vil,vil+m,cmp);

    int ans=kruskal(-1);

    //printf("%d\n",ans);

    mark=1;

    for(i=0;i<coun;i++)

    {

      int temp=kruskal(target[i]);

      //printf("temp=%d i=%d\n",temp,vil[target[i]].w);

      if(temp!=ans) {cnt++;worth+=vil[target[i]].w;}

    }

    printf("%d %d\n",cnt,worth);

  return 0;

}

  

你可能感兴趣的:(native)