挑战程序设计竞赛 P109 Conscription(征兵) POJ 3723

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值