跳到正文

个人记录

A*算法

Zou_exe约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年2月13日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

C++
#include <bits/stdc++.h>
using namespace std;

const int N=1010,M=200010;
int h[N],rh[N],to[M],w[M],ne[M],tot;
void add(int h[],int a,int b,int c){
  to[++tot]=b;w[tot]=c;
  ne[tot]=h[a],h[a]=tot;
}
int n,m,S,T,K;
int f[N],vis[N],cnt[N];
struct node{
  int s,v,d; //s排序,v点,d距离
  bool operator<(const node &x)const
    {return s>x.s;}
};

void dijkstra(){
  memset(f,0x3f,sizeof f); f[T]=0;
  priority_queue<pair<int,int>> q;
  q.push(make_pair(0,T));
  while(q.size()){
    pair<int,int> t=q.top(); q.pop();
    int u=t.second;
    if(vis[u])continue;
    vis[u]=true; //第一次出队时最小
    for(int i=rh[u]; i; i=ne[i]){
      int v=to[i];
      if(f[v]>f[u]+w[i]){
        f[v]=f[u]+w[i]; //估价函数
        q.push(make_pair(-f[v],v));
      }
    }
  }
}
int aStar(){
  priority_queue<node> q; //优先队列
  node a={f[S],S,0}; q.push(a);
  while(q.size()){
    node t=q.top(); q.pop();
    int u=t.v;
    cnt[u]++; //记录出队次数
    if(cnt[T]==K) return t.d; //边界
    for(int i=h[u]; i; i=ne[i]){
      int v=to[i], d=t.d+w[i];
      if(cnt[v]<K){
        node a={d+f[v],v,d};
        q.push(a);
      }
    }
  }
  return -1;
}
int main(){
  scanf("%d%d",&n,&m);
  for(int i=1; i<=m; i++){
    int a,b,c;
    scanf("%d%d%d",&a,&b,&c);
    add(h,a,b,c); add(rh,b,a,c); //反图
  }
  scanf("%d%d%d",&S,&T,&K);
  if(S==T) K++; //重合点,0是第一条
  dijkstra();
  printf("%d\n",aStar());
  return 0;
}

Luogu P1379 八数码难题

C++
#include <bits/stdc++.h>
using namespace std;

string goal="123804765"; //目标状态
int gx[]={-1,0,0,0,1,2,2,2,1}; //目标坐标
int gy[]={-1,0,1,2,2,2,1,0,0};
int dx[]={-1,0,1,0}, dy[]={0,1,0,-1};

int f(string s){ //估价函数: 曼哈顿距离之和
  int res=0;
  for(int i=0; i<9; i++){
    int t=s[i]-'0';
    if(t) res+=abs(i/3-gx[t])+abs(i%3-gy[t]);
  }
  return res;
}
int aStar(string start){
  unordered_map<string,int> d;
  priority_queue<pair<int,string>> q;
  q.push({-f(start),start}); d[start]=0;
  while(q.size()){
    auto a=q.top(); q.pop();
    string s=a.second;
    if(s==goal) return d[s]; //边界
    int k=s.find('0');
    int x=k/3, y=k%3; //行列坐标
    for(int i=0; i<4; i++){
      int a=x+dx[i], b=y+dy[i];
      if(a<0||a>=3||b<0||b>=3)continue;
      string t=s; swap(t[k],t[a*3+b]); //交换
      if(!d.count(t))
        d[t]=d[s]+1, q.push({-(d[t]+f(t)),t});
    }
  }
}
int main(){
  char c; string str;
  for(int i=0; i<9; i++)cin>>c,str+=c;
  cout<<aStar(str);
  return 0;
}
原文
抓取于
  1. Zou_exe

    6

  2. adolphshi

    wc凌晨3点写代码,太卷啦

  3. adolphshi

    %%%