zoj 1372

#include <iostream>
#include <string>
#include <string.h>
#include <map>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <vector>
#include <math.h>
#include <set>
#define Max(a,b) ((a)>(b)?(a):(b))
#pragma comment(linker, "/STACK:16777216")
using namespace std ;
typedef __int64 LL ;
const int Max_N = 58 ;
const int Max_M = 2508 ;
class Edge{
  public :
     int u  ;
     int v  ;
     int w  ;
     friend bool operator < (const Edge &A ,const Edge &B){
         return A.w < B.w  ;
     }
};

class App{
  private :
    Edge edge[Max_M] ;
    int N ;
    int M ;
    int father[Max_N] ;
  public :
    App(){} ;
    App(int ,int) ;
    void read() ;
    int find_father(int) ;
    int get_min() ;
    void out() ;
};

App::App(int n ,int m):N(n),M(m){
    for(int i = 1 ;i <= N ;i++)
        father[i] = i ;
}

void App::read(){
    for(int i = 1 ;i <= M ;i++)
       scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w) ;
}

int App::find_father(int x){
    if(x == father[x])
      return x ;
    else
      return father[x] = this->find_father(father[x]) ;
}

int App::get_min(){
    sort(edge+1,edge+1+M) ;
    int sum = 0 ;
    for(int i = 1 ;i <= M ;i++){
       int f_u = find_father(edge[i].u) ;
       int f_v = find_father(edge[i].v) ;
       if(f_u != f_v){
            sum += edge[i].w ;
            father[f_u] = f_v ;
       }
    }
    return  sum ;
}

void App::out(){
    printf("%d\n",this->get_min()) ;
}

int main(){
    int n , m ;
    while(scanf("%d",&n)&&n){
        scanf("%d",&m) ;
        App app(n,m) ;
        app.read() ;
        app.out() ;
    }
    return 0 ;
}

你可能感兴趣的:(MST)