最小生成树-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;
}
点赞