http://poj.org/problem?id=3723
这一题竟然用cin通不过, 用scanf 通过了。
POJ的编译器不支持struct这个用法: (edge) { e.u , e.v , e.cost }
#include <iostream>
#include <algorithm>
#include <stdio.h>
int N,M,R;
const int MM=20002;
using namespace std;
struct Edge{
int u;
int v;
int cost;
};
Edge es[50001];
int father[MM];
int ran[MM];
void init(int len){
for(int i=0;i<len;i++){
father[i] = i;
ran[i] = 0;
}
}
int findF(int x){
if(father[x] == x) return x;
else return father[x] = findF( father[x]) ;
}
void unit(int x, int y){
int root1= findF(x);
int root2= findF(y);
if(root1==root2) return;
if( ran[root1] < ran[root2]) father[root1] = root2;
else {
father[root2]=root1;
if( ran[root1] == ran[root2] ) ran[root1]++;
}
}
bool isSame(int x,int y){
return ( findF(x) == findF(y) );
}
bool cmp(Edge a, Edge b){
return (a.cost < b.cost);
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d%d",&N,&M,&R);
for(int i=1;i<=R; i++){
int a,b,c; scanf("%d%d%d",&a,&b,&c);
Edge d;d.u=a; d.v=N+b; d.cost=-c;
//es[i]=(Edge){a, N+b ,-c};
es[i]=d;
}
init(N+M);
int ans=0;
sort(es+1, es+R+1, cmp);
for(int i=1; i<=R;i++){
Edge e = es[i];
if( !isSame( e.u, e.v) )
{
unit( e.u, e.v );
//cerr << e.cost;
ans += e.cost;
}
}
printf("%d",10000*(N+M) + ans); printf("\n");
//cout << 10000*(N+M) + ans << endl;
}
return 0;
}
练习一下Kruskal