花瓣小跑 发表于 2024-8-9 23:57:29

【c++刷题笔记-图论】day62:Floyd 算法、A * 算法精讲

Floyd 算法

重点:多源最短路径算法,前的最短路径算法是单源的也就是只有一个起点。递推每个节点之间最短的路径


[*]时间复杂度: O(n^3)
[*]空间复杂度:O(n^2)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m, p1, p2, val;
    cin >> n >> m;

    vector<vector<int>> grid(n + 1, vector<int>(n + 1, 10005));// 因为边的最大距离是10^4

    for(int i = 0; i < m; i++){
      cin >> p1 >> p2 >> val;
      grid = val;
      grid = val; // 注意这里是双向图

    }
    // 开始 floyd
    for (int k = 1; k <= n; k++) {
      for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                grid = min(grid, grid + grid);
            }
      }
    }
    // 输出结果
    int z, start, end;
    cin >> z;
    while (z--) {
      cin >> start >> end;
      if (grid == 10005) cout << -1 << endl;
      else cout << grid << endl;
    }
}
A * 算法

重点:Astar关键在于启发式函数,也就是影响广搜大概 dijkstra 从容器(队列)里取元素的优先序次
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int moves;
int dir={-2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2};
int b1, b2;
// F = G + H
// G = 从起点到该节点路径消耗
// H = 该节点到终点的预估消耗

struct Knight{
    int x,y;
    int g,h,f;
    bool operator < (const Knight & k) const{// 重载运算符, 从小到大排序
   return k.f < f;
    }
};

priority_queue<Knight> que;

int Heuristic(const Knight& k) { // 欧拉距离
    return (k.x - b1) * (k.x - b1) + (k.y - b2) * (k.y - b2); // 统一不开根号,这样可以提高精度
}
void astar(const Knight& k)
{
    Knight cur, next;
        que.push(k);
        while(!que.empty())
        {
                cur=que.top(); que.pop();
                if(cur.x == b1 && cur.y == b2)
                break;
                for(int i = 0; i < 8; i++)
                {
                        next.x = cur.x + dir;
                        next.y = cur.y + dir;
                        if(next.x < 1 || next.x > 1000 || next.y < 1 || next.y > 1000)
                        continue;
                        if(!moves)
                        {
                                moves = moves + 1;

                // 开始计算F
                                next.g = cur.g + 5; // 统一不开根号,这样可以提高精度,马走日,1 * 1 + 2 * 2 = 5
                next.h = Heuristic(next);
                next.f = next.g + next.h;
                que.push(next);
                        }
                }
        }
}

int main()
{
    int n, a1, a2;
    cin >> n;
    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 = Heuristic(start);
      start.f = start.g + start.h;
                astar(start);
      while(!que.empty()) que.pop(); // 队列清空
                cout << moves << endl;
        }
        return 0;
}
总结

Floyd算法本质是动态规划,递推算出每个节点之间的最短隔断。可以用于有负权值的最短路径。
Astar 是一种 广搜的改良版。 有的是 Astar是 dijkstra 的改良版。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 【c++刷题笔记-图论】day62:Floyd 算法、A * 算法精讲