一.原题链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=203
二.题目大意:给定平面上N个城市的位置,计算连接这N个城市需要总路线最小长度。
三.思路:没有思路,最小生成树模板题,在某一本图论的书上看到的。注意输出格式就好,除第一个输出外,其他每个输出前面都有一个空行,还有保留2位小数。
四,代码:
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <queue> using namespace std; const int MAX_SIZE = 102, INF = 1<<30, MOD = 1000000007; struct Edge { int u, v; double weight; }; struct Point { double x, y; }; Point city[MAX_SIZE]; Edge edges[MAX_SIZE*MAX_SIZE]; int nodeNum, edgeNum, pre[MAX_SIZE]; void FUset() { memset(pre, -1, sizeof(pre)); } int Find(int x) { int root = x, save; while(pre[root] >= 0){ root = pre[root]; } while(x != root){ save = pre[x]; pre[x] = root; x = save; } return root; } void Union(int x, int y) { int xRoot = Find(x), yRoot = Find(y); //此时temp必为负数,负多少表示这棵树有几个节点 int temp = pre[xRoot] + pre[yRoot]; //把节点少的树合并在节点多的树下面。 if(pre[xRoot] > pre[yRoot]){ pre[xRoot] = yRoot; pre[yRoot] = temp; } else{ pre[yRoot] = xRoot; pre[xRoot] = temp; } } bool cmp(Edge a, Edge b) { return a.weight < b.weight; } double Kruskal() { int i, buildEdgeNum = 0, u, v; double sumWeight = 0; sort(edges, edges + edgeNum, cmp); FUset(); for(i = 0; i < edgeNum; i++){ u = Find(edges[i].u); v = Find(edges[i].v); if(u != v){ sumWeight += edges[i].weight; Union(u, v); } if(buildEdgeNum >= nodeNum - 1) break; } return sumWeight; } int main() { // freopen("in.txt", "r", stdin); int i, j, test = 1; while(cin>>nodeNum && nodeNum){ for(i = 0; i < nodeNum; i++) cin>>city[i].x>>city[i].y; edgeNum = 0; for(i = 0; i < nodeNum; i++) for(j = i + 1; j < nodeNum; j++){ edges[edgeNum].u = i; edges[edgeNum].v = j; edges[edgeNum].weight = sqrt( pow(city[i].x - city[j].x, 2) + pow(city[i].y - city[j].y, 2) ); edgeNum++; } if(test > 1) printf("\n"); printf("Case #%d:\nThe minimal distance is: %.2f\n", test++, Kruskal()); } }