[洛谷P1265]公路修建

题目传送门

这道题是稠密图,要用$Prim$,可以对照P1991的$Kruskal$,但在这里用会$MLE$会$TLE$。

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 #define re register
 6 #define rep(i, a, b) for (re int i = a; i <= b; ++i)
 7 #define repd(i, a, b) for (re int i = a; i >= b; --i)
 8 #define maxx(a, b) a = max(a, b);
 9 #define minn(a, b) a = min(a, b);
10 #define LL long long
11 #define INF (1 << 30)
12 
13 inline int read() {
14     int w = 0, f = 1; char c = getchar();
15     while (!isdigit(c)) f = c == '-' ? -1 : f, c = getchar();
16     while (isdigit(c)) w = (w << 3) + (w << 1) + (c ^ '0'), c = getchar();
17     return w * f;
18 }
19 
20 const int maxn = 5000 + 5;
21 
22 LL sqr(LL x) { return x * x; }
23 double dist(int x1, int y1, int x2, int y2) { return sqrt(sqr(x1-x2) + sqr(y1-y2)); }
24 
25 int n, x[maxn], y[maxn], v[maxn];
26 double ans = 0, t[maxn];
27 
28 int main() {
29     n = read();
30 
31     rep(i, 1, n) x[i] = read(), y[i] = read();
32 
33     memset(v, 0, sizeof(v));
34     int p = 1;
35     v[p] = 1;
36     rep(i, 1, n) t[i] = INF;
37     rep(kase, 1, n-1) {
38         int _min = 0;
39         rep(i, 1, n) 
40             if (!v[i]) {
41                 minn(t[i], dist(x[p], y[p], x[i], y[i]));
42                 if (!_min || t[i] < t[_min]) _min = i;
43             }
44         ans += t[_min];
45         v[_min] = 1;
46         p = _min;
47     }
48 
49     printf("%.2lf", ans);
50 
51     return 0;
52 }

猜你喜欢

转载自www.cnblogs.com/ac-evil/p/10325942.html
今日推荐