跳到正文

个人记录

A*算法

P25ffy约 10 分钟
原文
文章信息与版本

文章信息

收录
2026年7月23日
更新
2026年7月23日
篇幅
约 10 分钟

版本

  1. v1当前

A*算法

补充:优先队列BFS

优先队列BFS

PPTPPT 这么介绍:

适用场景:
解决边权为任意正整数的最短路径问题,突破了普通BFS只能处理边权为1的限制。
核心思想 利用“最小堆”维护节点,每次从队列中取出当前代价最小的节点进行扩展,确保首次访问即为最短路径。
时间复杂度:O((N + E) log N)(N为节点数,E为边数)

代码很简单,就把 queue 前面加一个 priority_。


例

题目大意

给定一张包含 NN 个城市和 MM 条道路的无向图,每个城市油价不同。有若干查询,每个查询给出油箱容量 CC 、起点 SS 和终点 TT ,要求计算从 SS 到 TT 的最小加油花费,需结合加油策略规划路径。

题目思路

采用最小堆(优先队列)实现 DijkstraDijkstra 算法,每次取出队列中花费最小的状态进行扩展。由于每个状态的代价非负,首次到达终点 (T,num)(T, num) 的状态即为全局最小花费。

ACcode?
C++
#include<iostream>
#define int double
using namespace std;
int n, m;
int p[N];
vector<pair<int, int> > v[N];
struct node{int x, f, val;};
bool operator < (const node &x, const node &y){return x.val > y.val;}
bool vis[N][105];

void bfs(int s, int e, int c){
	priority_queue<node> q;
	q.push({s, 0, 0});
	while(!q.empty()){
		node tm = q.top(); q.pop();
		int x = tm.x, f = tm.f, va = tm.val;
		if(x == e){
			cout << va << '\n';
			return;
		}
		if(vis[x][f])	continue;
		vis[x][f] = 1;
		if(f < c)	q.push({x, f + 1, va + p[x]});
		for(int i = 0; i < v[x].size(); i ++){
			int y = v[x][i].first, w = v[x][i].second;
			if(w > f)	continue;
			q.push({y, f - w, va});
			 
		}
	}
	cout << "impossible";
}

int main(){
	cin >> n >> m;
	for(int i = 1; i <= n; i ++)	cin >> p[i];
	for(int i = 1; i <= m; i ++){
		int x, y, z; cin >> x >> y >> z;
		x ++, y ++;
		v[x].push_back({y, z});
		v[y].push_back({x, z});
	}
	int q; cin >> q;
	while(q++){
		int x, y, z; cin >> x >> y >> z;
		z ++, y ++;
		bfs(y, z, x);
        //记得清空
	}
	return 123321;
}

什么是A*算法

A∗A* 算法的原理听起来可能有点不可思议,那就是提前预估出当前状态之后的代价,通过合在一起比较的方式来提提高代码效率。当然,预估的方式需要结合情境来自行判断 (实则是我不会说👉👈)\tiny{(实则是我不会说👉👈)},不过原则是可以低估但不能高估。
比如这道题的预估方式就是从终点计算到每个点的最短路径,遍历到不同点时才能预估出后来的最小代价。

题目大意

给定一个有向图,求从起点 SS 到终点 TT 的第 KK 短路的长度。

题目思路

统计终点的出队次数,当 cntcnt 刚好等于 KK 时输出。

ACcode?
C++
#include<bits/stdc++.h>
#define int double
using namespace std;
int n, m;
int st, ed, k;
vector<pair<int, int> > v[N], v2[N];
struct node{int x, dis, gj;};
bool operator < (const node &x, const node &y){
	if(x.dis + x.gj == y.dis + y.gj) return x.dis > y.dis;
	return x.dis + x.gj > y.dis + y.gj;
}
int h[N];
bool vis[N];
void avg(){
    //记得初始化h
	priority_queue<node> q;
	q.push({ed, 0, 0});
	while(!q.empty()){
		node fur = q.top(); q.pop();
		int x = fur.x;
		if(vis[x])	continue;
		vis[x] = 1;
		for(int i = 0; i < v2[x].size(); i ++){
			int y = v2[x][i].first, w = v2[x][i].second;
			if(h[y] <= h[x] + w)	continue;
			h[y] = h[x] + w;
			q.push({y, h[y], 0});
		}
	}
	return;
}
int cnt[N];
void ax(){
	if(h[st] == 0x3f3f3f3f){
		cout << -1;
		exit(0);
	}
	priority_queue<node> q;
	q.push({st, 0, h[st]});
	while(/**/){
		node fur = q.top(); q.pop();
		int x = fur.x;
		if(cnt[x] >= k)	continue;
		cnt[x] ++;
		if(x == ed && cnt[ed] == k){
			cout << fur.dis;
            //🤔
		}
		for(int i = 0; i < v[x].size(); i++){
			int y = v[x][i].first, w = v[x][i].second;
			if(cnt[y] >= k)	continue;
			q.push({y, fur.dis + w, h[y]});
		}
	}
	cout << -1;
	exit(0);
}

int main(){
	cin >> n >> m;
	for(int i = 1; i <= m; i ++){
		int x, y, z; cin >> x >> y >> z;
		v[x].push_back({y, z});
		v2[y].push_back({x, z});
	}
	cin >> st >> ed >> k;
	if(st == ed)	k++;
	avg();
	ax();
	return 0;
}

还有一道例题

题目大意

在一个3x3的棋盘上,有八个数字和一个空格(0)。每次可以将与空格相邻的数字移动到空格中。给定一个初始布局,求到达目标布局所需的最少移动次数。

题目思路

预估最少步数为每个点到目标位置的曼哈顿距离之和,再进行遍历。

ACcode?
C++
#include<iostream>
using namespace std;
const int dx[5] = {0, 0, 0, 1, -1};
const int dy[5] = {0, 1, -1, 0, 0};
string t = "123804765";
struct node{string st;int dis, gj;};
bool operator < (const node &x, const node &y){
	if(x.dis + x.gj == y.dis + y.gj)	return x.dis > y.dis;
	return x.dis + x.gj > y.dis + y.gj;
}
int calc(string s){
	int res = 0, len = s.size();
	for(int i = 0; i < len; i ++){
		if(s[i] == 0)	continue;
		int ti = t.find(s[i]);
		int ax = ti / 3 + 1, ay = ti % 3 + 1;
		int bx = i / 3 + 1, by = i % 3 + 1;
		res += abs(ax - bx) + abs(ay - by); 
	}
	return res;
}

map<string, bool> vis;
void ax(string s){
	priority_queue<node> q;
	q.push({s, 0, calc(s)});
	while(!q.empty()){
		node fur = q.top(); q.pop();
		string st = fur.st;
		if(vis.count(st))	continue;
		vis[st] = 1;
		if(st == t){
			cout << fur.dis;
			exit(0);
		}
		int si = st.find('0');
		int x = si / 3 + 1, y = si % 3 + 1;
		for(int i = 1; i <= 4; i ++){
			int xx = x + dx[i], yy = y + dy[i];
			if(xx < 1 || xx > 3 || yy < 1 || yy > 3)	continue;
			int ii = (xx - 1) * 3 + yy - 1;
			string s1 = st;
			swap(s1[si], s1[ii]);
			q.push({s1, fur.dis + 1, calc(s1)});
		}
	}
}

int main(){
	string s; cin >> s;
	cout << ax(t);
	return 0;
}

Thank\Huge{Thank} for\Huge{for} your\Huge{your} watching!!!\Huge{watching!!!}

原文