代码随想录-训练营-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星算法了。

相关推荐
椰萝Yerosius42 分钟前
[题解]2023CCPC黑龙江省赛 - Ethernet
算法·深度优先
IT猿手1 小时前
基于 Q-learning 的城市场景无人机三维路径规划算法研究,可以自定义地图,提供完整MATLAB代码
深度学习·算法·matlab·无人机·强化学习·qlearning·无人机路径规划
竹下为生3 小时前
LeetCode --- 448 周赛
算法·leetcode·职场和发展
未名编程3 小时前
LeetCode 88. 合并两个有序数组 | Python 最简写法 + 实战注释
python·算法·leetcode
Cuit小唐3 小时前
C++ 迭代器模式详解
c++·算法·迭代器模式
2401_858286113 小时前
CD37.【C++ Dev】string类的模拟实现(上)
开发语言·c++·算法
╭⌒心岛初晴4 小时前
JAVA练习题(2) 找素数
java·开发语言·算法·java练习题·判断素数/质数
懒懒小徐4 小时前
2023华为od统一考试B卷【二叉树中序遍历】
数据结构·算法·华为od
ghie90904 小时前
Kotlin中Lambda表达式和匿名函数的区别
java·算法·kotlin
_Itachi__5 小时前
LeetCode 热题 100 138. 随机链表的复制
算法·leetcode·链表