POJ 2449 Remmarguts' Date

A*模板题

#include<cstdio>
#include<queue>
#include<cstring>
#define MAXN 1005
#define MAXM 100005
using namespace std;
struct edge{int next,to,val;}e[MAXM<<1];
bool vis[MAXN];
int cnt_edge=0, cnt[MAXN], last1[MAXN], last2[MAXN], dis[MAXN];
void add(int a, int b, int c)
{
    e[++cnt_edge]=(edge){last1[a],b,c};
    last1[a]=cnt_edge;
    e[++cnt_edge]=(edge){last2[b],a,c};
    last2[b]=cnt_edge;
}
void SPFA(int beg)
{
    queue<int> q;
    memset(dis,64,sizeof(dis));
    dis[beg]=0;
    q.push(beg);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        vis[x]=0;
        for(int i = last2[x]; i; i=e[i].next)
        {
            int y=e[i].to;
            if(dis[x]+e[i].val<dis[y])
            {
                dis[y]=dis[x]+e[i].val;
                if(!vis[y])
                {
                    vis[y]=1;
                    q.push(y);
                }
            }
        }
    }
}
struct node
{
    int p, g, h;
    bool operator < (node a) const
    {
        return a.g+a.h<g+h;
    }
};
int A_star(int beg, int end, int k)
{
    priority_queue<node> q;
    node cur=(node){beg,0,dis[beg]}, nxt;
    q.push(cur);
    while(!q.empty())
    {
        cur=q.top();
        q.pop();
        cnt[cur.p]++;
        if(cnt[cur.p]>k)continue;
        if(cnt[end]==k)return cur.g;
        for(int i = last1[cur.p]; i; i=e[i].next)
        {
            nxt=(node){e[i].to,cur.g+e[i].val,dis[e[i].to]};
            q.push(nxt);
        }
    }
    return -1;
}
int main()
{
    int n, m, s, t, k;
    scanf("%d%d",&n,&m);
    for(int i = 1, a, b, c; i <= m; i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }
    scanf("%d%d%d",&s,&t,&k);
    SPFA(t);
    if(s==t)k++;//卧槽巨坑 
    int ans=A_star(s, t, k);
    printf("%d\n",ans);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值