1. 程式人生 > >POJ 1861 kruskal+優先佇列+並查集

POJ 1861 kruskal+優先佇列+並查集

//11161129	c00h00g	1861	Accepted	900K	110MS	G++	1462B	2013-01-06 13:00:00
//kruskal+優先佇列+並查集 
#include<cstdio>
#include<cstdlib>
#include<queue>
using namespace std;

int N,M,i,j,res;
struct Edge{
    int from,to,w;
    Edge(int x,int y,int z):from(x),to(y),w(z){}
    bool operator<(const Edge &rhs) const{
        return w>rhs.w;
    }
};
int parent[1005];
priority_queue<Edge> q;
queue<Edge> q_res;
void make_set(int x){parent[x]=x;}
int findset(int x){return parent[x]!=x?parent[x]=findset(parent[x]):x;}
void unionset(int x,int y){
     if(x<y) 
         parent[y]=x; 
     else 
         parent[x]=y;
}
void kruskal(){
    for(int i=1;i<=N;i++)
        make_set(i);
    while(!q.empty()){
        Edge tmp=q.top();q.pop();
        int x=findset(tmp.from);
        int y=findset(tmp.to);
        if(x!=y){
            if(res<tmp.w)
                res=tmp.w;
            unionset(x,y);
            q_res.push(tmp);
        } 
    }
}
void init(){
    while(!q.empty())
        q.pop();
    while(!q_res.empty())
        q_res.pop();
}
int main(){
    while(scanf("%d%d",&N,&M)!=EOF){
        init();
        res=-1;
        int a,b,wt;
        for(i=0;i<M;i++){
            scanf("%d%d%d",&a,&b,&wt);
            q.push(Edge(a,b,wt));
        }
        kruskal();
        printf("%d\n",res);
        printf("%d\n",q_res.size());
        while(!q_res.empty()){
            Edge tmp=q_res.front();q_res.pop();
            printf("%d %d\n",tmp.from,tmp.to);
        }
    }
    return 0;
}