http://acm.hdu.edu.cn/showproblem.php?pid=1875
Problem Description
相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现。现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全畅通!经过考察小组RPRush对百岛湖的情况充分了解后,决定在符合条件的小岛间建上桥,所谓符合条件,就是2个小岛之间的距离不能小于10米,也不能大于1000米。当然,为了节省资金,只要求实现任意2个小岛之间有路通即可。其中桥的价格为 100元/米。
Input
输入包括多组数据。输入首先包括一个整数T(T <= 200),代表有T组数据。
每组数据首先是一个整数C(C <= 100),代表小岛的个数,接下来是C组坐标,代表每个小岛的坐标,这些坐标都是 0 <= x, y <= 1000的整数。
每组数据首先是一个整数C(C <= 100),代表小岛的个数,接下来是C组坐标,代表每个小岛的坐标,这些坐标都是 0 <= x, y <= 1000的整数。
Output
每组输入数据输出一行,代表建桥的最小花费,结果保留一位小数。如果无法实现工程以达到全部畅通,输出”oh!”.
#include <stdio.h> #include <limits.h> #include <math.h> struct Pos { int x; int y; int operator- (const Pos& rhs) const { return (x - rhs.x) * (x - rhs.x) + (y - rhs.y) * (y - rhs.y); // use square value avoid to compare double type } }; static const int V = 100; Pos islands[V]; int G[V][V]; double Prim(int n) { int* dist = G[0]; // start from vertex0, use the first row of the matrix as the distance vector int c = n; double amount = 0.0; while (--c) { int add, min = INT_MAX; for (int i = 1; i < n; ++i) // find the non-connected vertex with the shortest the path { if (dist[i] != 0 && dist[i] < min) { add = i; min = dist[i]; } } if (min == INT_MAX) // all left vertices are isolated from the tree return -1; amount += sqrt((double)min); dist[add] = 0; // set to 0 present that this vertex has been connected to the tree for (int i = 1; i < n; ++i) // update the distance vector { if (G[add][i] < dist[i]) dist[i] = G[add][i]; } } return amount; } int main() { int t; scanf ("%d", &t); while (t--) { int c; scanf ("%d", &c); for (int i = 0; i < c; ++i) { scanf ("%d %d", &islands[i].x, &islands[i].y); G[i][i] = 0; for (int j = 0; j < i; ++j) { int d = islands[i] - islands[j]; if (d < 10 * 10 || d > 1000 * 1000) d = INT_MAX; G[i][j] = G[j][i] = d; } } double amount = Prim(c); if (amount == -1) printf ("oh!/n"); else printf ("%.1lf/n", amount * 100); } return 0; }