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 lz1 at 2010-04-10 13:30:53 on Problem 1287
#include<iostream> 
using namespace std;
const int M=10005,L=101;
int n,m,s,Rootx,Rooty,num,Sum;
struct MFTNode{
        int x,y;
        int w;
        }f[M];
int FATHER[L];

int comp(const void*a,const void*b){
    MFTNode *d,*q;
    d=(MFTNode*)a;
    q=(MFTNode*)b;
    return d->w>q->w?1:-1;
    }

void init_fopen(void){
     freopen ("PKU_1287.in","r",stdin);
     freopen ("PKU_1287.out","w",stdout);
     }

void solve_init(void){
     scanf ("%d",&m);
     Sum=0;num=0;
     memset(FATHER,0,sizeof (FATHER));
     for (int i=1;i<=m;i++)scanf ("%d%d%d",&f[i].x,&f[i].y,&f[i].w);
     qsort (f+1,m,sizeof (f[0]),comp);   
     }

int find(int k){
    if(!FATHER[k]) return k;
    return FATHER[k]=find(FATHER[k]);
    }

int main(void){
    init_fopen(); 
    scanf ("%d",&n);
    while (n){        
          solve_init(); 
          s=1;
          while (num<n-1&&s<=m){
              Rootx=find(f[s].x);
              Rooty=find(f[s].y);
              if(Rootx!=Rooty){
                 num++;
                 Sum+=f[s].w;
                 FATHER[Rooty]=Rootx;
                 }   
              s++;
              }
          printf ("%d\n",Sum);
          scanf ("%d",&n);
          }
    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