A*启发式搜索算法

A*算法中的估价函数

知识点二十五:启发式搜索算法

1、估价函数

用来估计当前点到终点的最短距离。
对于任意点u,d[u]+f[u] <= d[u] + g[u]
g[u]表示从点u到终点的真实距离
f[u]表示从点u到终点的估计距离
即估计的距离必须小于等于真实距离 ,f[state] <= g[state]

2、为什么A*是能保证终点的距离一定是最短的?

反证法:如果终点第一次出队时不是最短距离
那么在真实的最短路径上肯定存在一点u,这个点u到终点的真是距离为d[u] + g[u]
又因为估价函数:f[state] < g[state],所以说,我们可以得到下面这个不等式:
dist[end] > 最短路 >= d[u] + f[u]
这时我们就会发现,队列存在一个比dist[end]更小的点d[u] + f[u],而这个点又必须在dist[end]之前出队,这就与dist[end]先出队矛盾了。
由上,我们也可以得出A*算法合法的一个必要条件:0 <= f[state] <= g[state],如果f[state]太大,那么在错误的路径上可能会一直走下去,同样,f[state]不能小于0,假设f[]可以取到负无穷,那么就一条道走到黑了。

3、A*算法只能保证终点一定是最短路

 在上图中,我们从start开始拓展,此时出现两个点v和u,f[v] = 0, f[u] = g[u],由于d[u] = d[v] = 1,我们会选择d[]+f[]更小的点v,而点v后面的点的估价值都为0,所以我们会一直走下去知道点t。但我们发现这不是最短的路径,真正的最短路径应该是走u。此时我们沿着一条非最短路径继续走下去。

由于这条路径不是最短路,那么它一定会走到以点p(t到end是一条非常长的路径),此时d[p]+f[p] > d[u] + g[u],之后从点u开始拓展,直到走完真正的最短路径。

解释一下:由于从v出发的并不是最短路,那么,肯定至少存在一点p使得d[p]+f[p]>min_dist,(假设最极端的情况,这条路径上的估价值全为0,那么也肯定至少存在这个点p,因为这条路径的真实距离肯定小于最短距离)所以说,即便我们走的是一条错误的路径,也肯定会存在某个时刻我们走到一个点被拨乱反正,它的d[]+g[]不再是最小值,也就不再是优先队列的队头,此时可能会被另一条错误的路径拓展,或者被真正的路径拓展。

另外,上面的例子也说明了,A*算法只有终点在出队时是最小值,而其他点出队时并不能确保最小值,所以说在A*的优先队列中,一个点可以多次入队(被拓展多次)!(上例的t点第一次出队时的距离是4,但实际的最短距离应该是2)其原因在于f[]估价函数。我们的估价函数是以终点为目标的估计值,而不是以整体的估计值,所以我们只能保证终点的正确性。这也说明了A*不需要判重。

4、A*算法必须保证数据有解

如果A*算法搜索一条没有解的路径,那么它会搜索所有点,这和朴素BFS相同,但是A*算法使用的是优先队列,每次入队出队的时间复杂度是O(logn)的,而朴素DFS是O(1)的,甚至不如朴素的。

5、数据结构

  • A*采用优先队列,队列的第一关键字是{当前点的距离+估价距离}
  • 形式上和dijkstra类似,但本质上dijkstra没啥关系。
  • 当终点第一次出队时就是最小值

6、else

  • A*算法可以处任意边权问题(不包括负值回路)
  • dijkstra算法可以看做所有估价值都为0的A*算法
  • A*算法的核心在于估价函数的确定,可以说估价函数就是A*的核心


 


179. 八数码 - AcWing题库

 朴素BFS做法,最小步数模型

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;

string start, en = "12345678x";
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};
char ch[] = {'l', 'u', 'r', 'd'};
unordered_map<string, pair<string, char> > pre;
unordered_map<string, int> dist;

int bfs()
{
    queue<string> q;
    q.push(start);
    dist[start] = 0;
    
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        
        int pos = t.find('x'), distance = dist[t];
        int sx = pos / 3, sy = pos % 3;
        
        for(int i = 0; i < 4; i ++ )
        {
            int a = sx + dx[i], b = sy + dy[i];
            if(a < 0 || a >= 3 || b < 0 || b >= 3)  continue;//如果越界
            string tt = t;
            swap(tt[pos], tt[a * 3 + b]);
            if(dist.count(tt))   
            {
                // cout << "count: " << tt << endl;
                continue;
            }
            dist[tt] = distance + 1;
            pre[tt] = {t, ch[i]};
            if(tt == en)    return dist[tt];
            q.push(tt);
            // cout << "tt:" << tt << endl;
        }
    }
    return -1;
}

int main()
{
    for(int i = 0; i < 9; i ++ )
    {
        char ch;
        cin >> ch;
        start += ch;
    }
    
    // cout << start << endl;
    // cout << en << endl;
    
    int t = bfs();
    if(t == -1) puts("unsolvable");
    else
    {
        // cout << "true" << endl;
        string res = "";
        while(en != start)
        {
            res += pre[en].y;
            en = pre[en].x;
        }
        // cout << "res: ";
        cout << res << endl;
    }


    
    return 0;
}

A*做法

注意在使用A*算法的时候,我们必须得先判断答案是否有解,所以在开始要特判一下。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <unordered_map>

#define x first
#define y second

using namespace std;

typedef pair<int, string> PIS;

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
char op[4] = {'u', 'r', 'd', 'l'};
string start, en = "12345678x", seq;

int f(string s)
{
    int d = 0;
    for(int i = 0; i < 9; i ++ )
    {
        int t = s.find(en[i]);
        d += abs(i / 3 - t / 3) + abs(i % 3 - t % 3);
    }
    return d;
}

string A_bfs()
{
    priority_queue<PIS, vector<PIS>, greater<PIS> > q; 
    unordered_map<string, int> dist;
    unordered_map<string, pair<string, char> > pre;
    
    q.push({f(start), start});
    dist[start] = 0;
    
    while(q.size())
    {
        auto t = q.top();   q.pop();
        
        string str = t.y;
        
        //下面不要去为t.x,因为t.x存的是真实距离dist[]+估计距离f()
        //而我们想要的只是真实距离dist
        int distance = dist[str];
        
        if(str == en) break;
        
        int pos = str.find('x');
        int sx = pos / 3, sy = pos % 3;
        
        for(int i = 0; i < 4; i ++ )
        {
            int a = sx + dx[i], b = sy + dy[i];
            if(a < 0 || a >= 3 || b < 0 || b >= 3)  continue;//越界
            string tt = str;
            swap(tt[pos], tt[a * 3 + b]);
            if(!dist.count(tt) || dist[tt] > distance + 1)
            {
                dist[tt] = dist[str] + 1;
                q.push({distance + f(tt), tt});
                pre[tt] = {str, op[i]};
            }
        }
    }
    
    string res = "";
    while(en != start)
    {
        res += pre[en].y;
        en = pre[en].x;
    }
    reverse(res.begin(), res.end());
    return res;
}

int main()
{
    for(int i = 0; i < 9; i ++ )
    {
        char ch;    cin >> ch;
        start += ch;
        if(ch != 'x')   seq += ch;
    }
    
    int cnt = 0;
    for(int i = 0; i < 8; i ++ )
        for(int j = i + 1; j < 8; j ++ )
            if(seq[i] > seq[j]) 
                cnt ++ ;
    
    if(cnt & 1) puts("unsolvable");
    else    cout << A_bfs() << endl;
    
    return 0;
}    
    


模板题:178. 第K短路 - AcWing题库

题目让我们求从S到T第k条最短路,我们可以用反向建图,用dijkstra算法预处理T到每个点的最短路

然后用A*算法搜索,在A*中,我们已经证得终点第一次出队时一定是最短的,那么终点第K次出队,就是第K短的,和第一次出队的证明类似,这里不与予证明。

估价函数:由于我们已经预处理出来每个点到终点的最短路,那么我们可以直接用这个最短路作为估价函数,且可知这个估价函数很高效! 

每条最短路中至少包含一条边,所以当 S == T 的时候,需要让 K ++,意思是第一次直接由S到T的路径不算

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;
typedef pair<int, PII> PIII;

const int N = 1010, M = 200010;

int S, T, K, n, m;
int rh[N], h[N], e[M], ne[M], w[M], idx;
int dist[N], cnt[N];
bool st[N];

void add(int h[], int a, int b, int c)  // 添加一条边a->b
{
    w[idx] = c;
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}

void dijkstra()
{
    priority_queue<PII, vector<PII>, greater<PII>> q;
    memset(dist, 0x3f, sizeof dist);    
    
    q.push({0, T});
    dist[T] = 0;
    
    while(q.size())
    {
        auto t = q.top();   q.pop();
        int ver = t.y;
        if(st[ver]) continue;
        st[ver] = true;
        
        for(int i = rh[ver]; ~i ; i = ne[i])
        {
            int j = e[i];
            if(dist[j] > dist[ver] + w[i])
            {
                dist[j] = dist[ver] + w[i];
                q.push({dist[j], j});
            }
        }
    }
}

int astar()
{
    priority_queue<PIII, vector<PIII>, greater<PIII> >q;
    q.push({dist[S], {0, S}});
    
    while(q.size())
    {
        auto t = q.top();   
        q.pop();
        
        int ver = t.y.y, distance = t.y.x;
        cnt[ver] ++ ;
        if(cnt[T] == K) return distance;
        
        for(int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if(cnt[j] < K)
                q.push({distance + w[i] + dist[j], {distance + w[i], j}});
        }
    }
    
    return -1;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin.tie(nullptr);
    
    memset(h, -1, sizeof h);
    memset(rh, -1, sizeof rh);
    
    cin >> n >> m;
    while (m -- )
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(h, a, b, c);
        add(rh, b, a, c);
    }
    
    cin >> S >> T >> K;
    
    if(S == T) K ++ ;
    
    dijkstra();
    cout << astar() << endl;
    
    return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值