Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

大水题,kruskal秒杀

Posted by geek0 at 2012-08-04 00:01:54 on Problem 1287
/*
 * Problem: POJ 2387
 * Author: geek 7
 * Time: 2012.8.3 9:52 PM
 * State:
 * Memo: kruskal & 并查集
*/
#include<cstdio>
#include<cstring>
#include<cstdlib>
const int maxn=5100;
int fa[maxn];

struct node
{
 int x,y;
 int va;
}a[maxn];

int cmp(const void *a,const void *b)
{
  return ((node *)a)->va-((node *)b)->va;
}

int find(int x)
{
  if(x!=fa[x])
  {
    fa[x]=find(fa[x]);
  }
  return fa[x];
}

void init(int n)
{
  int i;
  for(i=0;i<n;i++)
   scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].va);

  qsort(a,n,sizeof(node),cmp);

  for(i=0;i<maxn;i++)
   fa[i]=i;
}

void kruskal(int n,int m)
{
  int i,ct=0,ans=0,x,y;
  for(i=0;i<n;i++)
  {
    x=find(a[i].x);
    y=find(a[i].y);
    if(x!=y)
    {
      ct++;
      ans+=a[i].va;
      if(ct==m-1)
       break;
      fa[y]=x;
    }
  }
  printf("%d\n",ans);
}

int main()
{
  int m,n;
  while(1)
  {
   scanf("%d",&m);
   if(m==0)
    break;
   scanf("%d",&n);
   init(n);
   kruskal(n,m);
  }
  return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator