POJ 3723 Conscription

将问题做一下转换,如果两个人之间有关系就在两个人之间连一条边,边的权值是题目给的关系数值的相反数,假设没有关系的人之间的边的权值是0,那么问题就变成了在完全图里面找最小生成树,最小生成树的所有边的权值和加上(M+N)*10000就是最后的答案,当然没有必要构造出完全的最小生成树,如果包含关系的边用完了,就不用再用权值为0的边继续构造最小生成树了,因为这样对最小生成树的总权值和没有影响,用优先队列优化一下克鲁斯卡尔算法就OK了。

#include <stdio.h>
#include <queue>
using namespace std;
             
int merge_set[20005];
int depth[20005];

void merge(int root_a, int root_b){
	if(root_a < root_b)
		merge_set[root_a] = root_b;
	else{
		merge_set[root_b] = root_a;
		if(depth[root_a] == depth[root_b])
			depth[root_a]++;
	}
}

int get_root(int son){
	if(merge_set[son] == son)
		return son;

	return merge_set[son] = get_root(merge_set[son]);
}

typedef struct edge{
	int v1;
	int v2;
	int len;

	edge(int v1, int v2, int len){
		this->v1 = v1;
		this->v2 = v2;
		this->len = len;
	}
}edge;

priority_queue<edge> pq;


bool operator < (const edge &a, const edge &b){
	return a.len > b.len;
}

void solve(int total_v){
	int total_cost, cnt;
	edge e(0,0,0);

	total_cost = 10000*total_v;
	cnt = 0;
	while(1){
		if(cnt == total_v-1)
			break;
		if(pq.empty())
			break;

		e = pq.top(); pq.pop();
		if(get_root(e.v1) == get_root(e.v2))
			continue;

		total_cost += e.len;
		cnt++;
		merge(get_root(e.v1), get_root(e.v2));
	}
	printf("%d\n", total_cost);
}


int main(void){
	int case_n, N, M, R, i;
	int male, fmale, value;

	//freopen("input.dat", "r", stdin);
	scanf("%d", &case_n);

	while(case_n--){
		scanf("%d %d %d", &N, &M, &R);
		for(i=0; i<M+N; i++){
			merge_set[i] = i;
			depth[i] = 1;
		}
		
		while(!pq.empty())
			pq.pop();

		while(R--){
			scanf("%d %d %d", &fmale, &male, &value);
			male += N;
			pq.push(edge(male, fmale, -1*value));
		}
		solve(M+N);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值