很好的一道bfs题目,到达岸边可以看成是最后一步

#include<bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;
int n, dist[N], pre[N];
double d, dis;
struct node{
    double x, y;
    int pos;
    double f;
}a[N];
stack<int> sta;

//保证最小的最先搜到
bool cmp(node s1, node s2){
    return s1.f < s2.f;
}

void bfs(){
    queue<node> q;
    memset(dist, 0x3f, sizeof dist);
    //把所有的可能的第一步都给它放进来
    for(int i = 1; i <= n; i++){
        if(a[i].f > 7.5 && a[i].f <= 7.5 + d){
            q.push(a[i]);
            dist[i] = 1;
            pre[i] = -1;
        }
    }
    while(!q.empty()){
        auto t = q.front();
        q.pop();
        int xx = t.x, yy = t.y, poss = t.pos;
        //结束条件,当距离岸边的距离小于等于d时,就准备跳出循环
        if(xx > 0){
            if(yy > 0) dis = min(50.0 - xx, 50.0 - yy);
            else dis = min(50.0 + yy, 50.0 - xx);
        }
        else{
            if(yy > 0) dis = min(50 - yy, 50 + xx);
            else dis = min(50 + yy, 50 + xx);
        }
        if(dis <= d){
            if(dist[n + 1] == 0x3f3f3f3f){
                dist[n + 1] = dist[poss] + 1;
                pre[n + 1] = poss;
                break; 
            }
        }
        for(int i = 1; i <= n; i++){
            if(dist[i] == 0x3f3f3f3f && a[i].f > 7.5){
                double dst = sqrt((xx - a[i].x) * (xx - a[i].x) + (yy - a[i].y) * (yy - a[i].y));
                if(dst <= d){
                    dist[i] = dist[poss] + 1;
                    pre[i] = poss; 
                    q.push(a[i]);
                }
            }
        }
    }
}

void print(int x){
    if(pre[x] == -1){
        sta.push(x);
        return;
    }
    sta.push(x);
    print(pre[x]);
}

signed main(){
    cin >> n >> d;
    for(int i = 1; i <= n; i++){
        cin >> a[i].x >> a[i].y;
        a[i].f = sqrt(1.0 * a[i].x * a[i].x + 1.0 *a[i].y * a[i].y);
    }
    //要考虑一步跳出去的情况
    if(d >= 50){
        cout << 0 << endl;
        return 0;
    }
    //sort这一步非常妙,这样保证了第一步距离最近的点最先被搜索到
    sort(a + 1, a + 1 + n, cmp);
    for(int i = 1; i <= n; i++) a[i].pos = i;
    bfs();
    if(dist[n + 1] == 0x3f3f3f3f){
        cout <<"0" << endl;
        return 0;
    }
    cout << dist[n + 1] << endl;
    print(n + 1);
    //因为搜索的时候,多搜索了最后一步,但是实际上最后一步已经到达岸边
    //所以就不用输出最后一步位置了
    while(sta.size() > 1){
        auto t = sta.top();
        cout << a[t].x <<" " << a[t].y << endl;
        sta.pop();
    }
    return 0;
}

原文地址:http://www.cnblogs.com/N-lim/p/16906958.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性