POJ - 2253 Frogger

POJ - 2253 题目链接
最短路的最大值问题
本来一开始用Dijkstra来写的,后来代码乱了。然后想一想还能用什么方法来写,好像kruskal好像也能处理,
每次加完边判断 0,1这两个点在不在同一颗树上,如果在的话直接跳出for循环,不在的话继续加边。
思路好像行得通,但是我在这种思路下wa了好几次,原因之一就是并查集没学好,判断两个点在不在同一颗数我直接用fa[0] == fa[0]了,这个bug我一直没发现,然后通过无数个输出中间变量来打表才把这个bug给找出来。

//Powered by CK
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int N1 = 210, N2 = 4e4 + 10;
int fa[N1], n, m;
double x[N1], y[N1], ans;
struct Road {
    int x, y;
    double w;
    // Road(int a, int b, double c) : x(a), y(b), w(c) {}
    bool operator < (const Road & t) const {//省的去写cmp了,
        return w < t.w;
    }
}road[N2];
double get_len(double x1, double y1, double x2, double y2) {
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
void init() {
    for(int i = 0; i < n; i++)  fa[i] = i;
    ans = 0;
}
int find(int x) {
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int main() {
    // freopen("in.txt", "r", stdin);
    int xx = 1;
    while(scanf("%d", &n) && n) {
        for(int i = 0; i < n; i++)
            scanf("%lf %lf", &x[i], &y[i]);
        m = 0;
        for(int i = 0; i < n; i++)
            for(int j = i + 1; j < n; j++) {
                road[m].x = i, road[m].y = j;
                road[m++].w= get_len(x[i], y[i], x[j], y[j]);
            }
        sort(road, road + m);
        init();
        for(int i = 0; i < m; i++) {
            int fx = find(road[i].x);
            int fy = find(road[i].y);
            if(fx != fy) {
                fa[fx] = fy;
                ans = road[i].w;
            }
            //if(fa[0] == fa[1])    break;//这一句就是我wa了好几次的罪魁祸首。
            if(find(0) == find(1))    break;
        }
        printf("Scenario #%d\nFrog Distance = %.3f\n\n", xx++, ans);
    }
    return 0;
}
posted @ 2020-01-05 18:55  lifehappy  阅读(59)  评论(0编辑  收藏  举报