最小生成树-Kruscal-POJ 1258 Agri-Net

POJ 1258题目简单,背景忽略,就是直接裸露的使用kruscal方法求最短路。

虽然简单,但是深深的体会了这个题目的恶意,简直了。。。就是如下的代码:

for (int i = 0; i < k; i++) {
			int x = edge[i].s, y = edge[i].e, w = edge[i].cost;
			int tx = findRoot(x), ty = findRoot(y);
			if (tx != ty) {
				unite(tx, ty);
				ans += w;
			}
		}

我原来是没有使用替代变量,而是直接使用edge[i],没想到,就是因为这个,不停地超时。。。。使用替代变量就是16MS,简直了。。。。代码如下:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

using namespace std;
const int maxn = 105;

int N;
int pre[maxn];
int r[maxn];

struct D {
	int s, e, cost;
	D(){}
	D(int s, int e, int cost): s(s), e(e), cost(cost){}
	bool operator < (const D& d) const {return cost < d.cost;}
}edge[10010];

int findRoot(int i) {
	return i == pre[i] ? i : (pre[i] = findRoot(pre[i]));
}

void unite(int i, int j) {
	if (r[i] > r[j]) pre[j] = pre[i];
	else {
		pre[i] = pre[j];
		if (r[i] == r[j]) r[j]++;
	}
}

int main() {
	while (scanf("%d", &N) == 1) {
		int k = 0, cost;
		memset(r, 0, sizeof(r));
		for (int i = 1; i <= N; i++) pre[i] = i;
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				scanf("%d", &cost);
				if (i < j) edge[k++] = D(i, j, cost);
			}
		}
		int ans = 0;
		sort(edge, edge + k);
		for (int i = 0; i < k; i++) {
			int x = edge[i].s, y = edge[i].e, w = edge[i].cost;
			int tx = findRoot(x), ty = findRoot(y);
			if (tx != ty) {
				unite(tx, ty);
				ans += w;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值