1. 程式人生 > >poj2449(Astar模板)

poj2449(Astar模板)

思路:第k最短路,Astar板子題,dijkstra跑反向圖的評估函式就好了。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <bitset>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll inff = 0x3f3f3f3f3f3f3f3f;
#define FOR(i,a,b) for(int i(a);i<=(b);++i)
#define FOL(i,a,b) for(int i(a);i>=(b);--i)
#define REW(a,b) memset(a,b,sizeof(a))
#define inf int(0x3f3f3f3f)
#define si(a) scanf("%d",&a)
#define sl(a) scanf("%I64d",&a)
#define sd(a) scanf("%lf",&a)
#define ss(a) scanf("%s",a)
#define mod ll(998244353)
#define pb push_back
#define eps 1e-6
#define lc d<<1
#define rc d<<1|1
#define Pll pair<ll,ll>
#define P pair<int,int>
#define pi acos(-1)
const int N=100008;
struct as{
int x;
ll v;};
ll d[N],s,t,k,cnt[N];
struct node{
    ll id,dist;
    bool operator<(const node a) const{
    return dist+d[id]>a.dist+d[a.id];}
};
vector<as> g[N],g1[N];
void djk(int s)
{
    priority_queue<P,vector<P>,greater<P> >q;
    REW(d,inff);
    d[s]=0;
    q.push(P(d[s],s));
    while(!q.empty())
    {
        P p=q.top();q.pop();
        int v=p.second;
        if(d[v]<p.first) continue;
        for(int i=0;i<g1[v].size();i++)
        {
            as e=g1[v][i];
            if(d[e.x]>d[v]+e.v)
            {
                d[e.x]=d[v]+e.v;
                q.push(P(d[e.x],e.x));
            }
        }
    }
}
int Astar()
{
    if(d[s]==inff) return -1;
    REW(cnt,0);
    node tmp=node{s,0},tt;
    priority_queue<node,vector<node> >qw;
    qw.push(tmp);
    while(!qw.empty())
    {
        tmp=qw.top();qw.pop();
        cnt[tmp.id]++;
        if(cnt[t]==k) return tmp.dist;
        if(cnt[tmp.id]>k) continue;
        for(int i=0;i<g[tmp.id].size();i++)
        {
            int v=g[tmp.id][i].x;
            tt=node{v,tmp.dist+g[tmp.id][i].v};
            qw.push(tt);
        }
    }
    return -1;
}
int main()
{
    cin.tie(0);
    cout.tie(0);
    ll n,m,x,y,z;
    while(cin>>n>>m)
    {
        FOR(i,1,n) g[i].clear(),g1[i].clear();
        FOR(i,1,m)
        {
            sl(x),sl(y),sl(z);
            g[x].pb(as{y,z});
            g1[y].pb(as{x,z});
        }
        cin>>s>>t>>k;
        if(s==t) k++;
        djk(t);
        cout<<Astar()<<endl;
    }
    return 0;
}