POJ2253 Frogger Kruscal C语言

题目:http://poj.org/problem?id=2253

题目大意:找到从点1到点2的某一条路中最长边,使最长的这条边尽量短

算法:Kruscal

思路:搜了题解……找最小生成树,加入某条边后点1和点2联通了,那么这条边就是所求边

提交状况:OLE 1次, WA n次, AC 1次

总结:从昨天上午纠结到今天中午……就是懒得建图……并查集也有问题,先是细节,再是路径压缩不对。我WA了一上午的题啊,同学过来不到两分钟就发现错误了……我掩面逃走……

AC code :

View Code
 1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <math.h>
5 #include <algorithm>
6 using namespace std;
7
8 #define MAXN 300
9 #define MAXE 90000
10 #define EPS 1e-6
11
12 typedef struct GRAPH {
13 double x, y;
14 }graph;
15
16 graph point[MAXN];
17 int father[MAXN];
18
19 typedef struct EDGE {
20 int u, v;
21 double len;
22 }edges;
23
24 edges edge[MAXE];
25 int cnt = 0;
26
27 void Clear() {
28 cnt = 0;
29 }
30
31 void INsert(int n) {
32 int i, j;
33 double x, y;
34 for(i = 1; i <= n; i++) {
35 scanf("%lf%lf", &x, &y);
36 point[i].x = x; point[i].y = y;
37 father[i] = i;
38 }
39 for(i = 1; i <= n; ++i)
40 for(j = i + 1; j <= n; ++j) {
41 edge[++cnt].u = i;
42 edge[cnt].v = j;
43 edge[cnt].len = sqrt((point[i].x - point[j].x) * (point[i].x - point[j].x)
44 + (point[i].y - point[j].y) * (point[i].y - point[j].y)) + EPS;
45
46 }
47 }
48
49 int cmp(edges &a, edges &b) {
50 return a.len < b.len;
51 }
52
53 int Find(int u) {
54 return father[u] = u == father[u] ? u : Find(father[u]); //路径压缩要仔细
55 }
56
57 void Union(int u, int v) {
58 father[v] = u;
59 }
60
61 double MLT() {
62 int i;
63 int fu, fv;
64 for(i = 1; i <= cnt; ++i) {
65 fu = Find(edge[i].u);
66 fv = Find(edge[i].v);
67 if(fu != fv)
68 Union(fu, fv);
69 if(Find(1) == Find(2)) // 注意是Find(1) == Find(2), 不是father[1] == father[2],
70 return edge[i].len; //根节点相同父节点不一定相同
71 }
72 return 0.0;
73 }
74
75 int main() {
76 int n;
77 int count = 0;
78 while(scanf("%d", &n), n) {
79 Clear();
80 INsert(n);
81 sort(edge + 1, edge + cnt + 1, cmp);
82 printf("Scenario #%d\nFrog Distance = %.3f\n\n", ++count, MLT() + EPS);
83 }
84 return 0;
85 }
posted @ 2011-07-23 13:49  cloehui  阅读(183)  评论(0编辑  收藏  举报