代码随想录-训练营-day52

97. 小明逛公园 (kamacoder.com)

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n,m,u,v,w;
    cin>>n>>m;
    vector<vector<vector<int>>> grid(n+1,vector<vector<int>>(n+1,vector<int>(n+1,10001)));
    while(m--){
        cin>>u>>v>>w;
        grid[u][v][0]=w;
        grid[v][u][0]=w;
    }
    for(int k=1;k<=n;++k){
        for(int i=1;i<=n;++i){
            for(int j=1;j<=n;++j){
                grid[i][j][k]=min(grid[i][k][k-1]+grid[k][j][k-1],grid[i][j][k-1]);
            }
        }
    }
    int num,start,end;
    cin>>num;
    while(num--){
        cin>>start>>end;
        if(grid[start][end][n]==10001){
            cout<<-1<<endl;
        }
        else{
            cout<<grid[start][end][n]<<endl;
        }
    }
    return 0;
}

之前我们涉及的迪杰斯特拉算法和贝尔曼福德算法都是针对单源最短路径的,而当问题来到多源的最短路径时这两种算法就不适用了。针对多源最短路径问题,我们一般用floyd算法或者A星算法。

127. 骑士的攻击 (kamacoder.com)

cpp 复制代码
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int moves[1001][1001];
int b1,b2;
const vector<pair<int,int>> dirs={{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}};
struct Knight{
    int x,y;
    int g,h,f;
    bool operator < (const Knight& k)const{
        return k.f<f;
    }
};
priority_queue<Knight> pq;
int OlaDis(const Knight& k){
    return (k.x-b1)*(k.x-b1)+(k.y-b2)*(k.y-b2);
}
void astar(const Knight& k){
    Knight cur,nex;
    pq.push(k);
    while(!pq.empty()){
        cur=pq.top();
        pq.pop();
        if(cur.x==b1&&cur.y==b2)break;
        for(auto [dx,dy]:dirs){
            nex.x=cur.x+dx;
            nex.y=cur.y+dy;
            if(nex.x<1||nex.x>1000||nex.y<1||nex.y>1000)continue;
            if(!moves[nex.x][nex.y]){
                moves[nex.x][nex.y]=moves[cur.x][cur.y]+1;
                nex.g=cur.g+5;
                nex.h=OlaDis(nex);
                nex.f=nex.g+nex.h;
                pq.push(nex);
            }
        }
    }
}
int main(){
    int n;
    cin>>n;
    int a1,a2;
    while(n--){
        cin>>a1>>a2>>b1>>b2;
        memset(moves,0,sizeof(moves));
        Knight start;
        start.x=a1;
        start.y=a2;
        start.g=0;
        start.h=OlaDis(start);
        start.f=start.g+start.h;
        astar(start);
        while(!pq.empty())pq.pop();
        cout<<moves[b1][b2]<<endl;
    }
    return 0;
}

这个就是A星算法了。

相关推荐
地平线开发者10 小时前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮10 小时前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者10 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考11 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx14 小时前
CART决策树基本原理
算法·机器学习
Wect14 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱15 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
Gorway1 天前
解析残差网络 (ResNet)
算法
拖拉斯旋风1 天前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect1 天前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript