Problem : 1233 ( 还是畅通工程 ) Judge Status : Accepted
RunId : 21246904 Language : G++ Author : hnustwanghe
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int N = 100 + 5;
typedef struct node{
int from,to,val;
node(int from=0,int to=0,int val=0):from(from),to(to),val(val){}
bool operator < (const node x)const {
return val > x.val;
}
}Node;
int pre[N];
int Find(int x){
return pre[x]==x?x:(pre[x]=Find(pre[x]));
}
bool Merge(int x,int y){
x = Find(x),y = Find(y);
if(x!=y) pre[x] = y;
return x!=y?true:false;
}
priority_queue<Node> Q;
int Kruskal(int n){
Node t;
int tmp = n*(n-1)/2,a,b,val,ans=0,cnt=0;
for(int i=1;i<=tmp;i++){
scanf("%d %d %d",&a,&b,&val);
Q.push(Node(a,b,val));
}
while(!Q.empty()){
t = Q.top();Q.pop();
if(Merge(t.from,t.to)){
ans += t.val;
cnt++;
if(cnt == n-1) return ans;
}
}
return ans;
}
int main(){
int n;
while(scanf("%d",&n)==1 && n){
while(!Q.empty()) Q.pop();
for(int i=0;i<N;i++) pre[i] = i;
printf("%d\n",Kruskal(n));
}
}
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int N = 100 + 5;
typedef struct node{
int from,to,val;
node(int from=0,int to=0,int val=0):from(from),to(to),val(val){}
bool operator < (const node x)const {
return val > x.val;
}
}Node;
int pre[N];
int Find(int x){
return pre[x]==x?x:(pre[x]=Find(pre[x]));
}
bool Merge(int x,int y){
x = Find(x),y = Find(y);
if(x!=y) pre[x] = y;
return x!=y?true:false;
}
priority_queue<Node> Q;
int Kruskal(int n){
Node t;
int tmp = n*(n-1)/2,a,b,val,ans=0,cnt=0;
for(int i=1;i<=tmp;i++){
scanf("%d %d %d",&a,&b,&val);
Q.push(Node(a,b,val));
}
while(!Q.empty()){
t = Q.top();Q.pop();
if(Merge(t.from,t.to)){
ans += t.val;
cnt++;
if(cnt == n-1) return ans;
}
}
return ans;
}
int main(){
int n;
while(scanf("%d",&n)==1 && n){
while(!Q.empty()) Q.pop();
for(int i=0;i<N;i++) pre[i] = i;
printf("%d\n",Kruskal(n));
}
}