【POJ 2449】Remmarguts's Date (A*搜索第k短路)

来源:互联网 发布:项目评价软件 编辑:程序博客网 时间:2024/05/16 01:36

传送门

    POJ 2449
    题意:给出一张图,求两点S、T之间的第K短路。

I think

    学习A*搜索好文力荐:http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx
    A*搜索从S第k次搜到T,该路径的总长即答案。
    注意,根据题目要求:第K短路径可以重复经过某点。若数据给出两个的S==T,则++K。
    此外还遇到一个错误,反映自己对于STL的优先队列理解不深。在优先队列中存放的是自定义的结构体时,结构体需要重载运算符。优先队列就是堆。若定义队列为大根堆,则在结构体中重载<,反之同理。

bool operator < (const Astar&x) const {        return (f!=x.f)?(x.f<f):(x.g<g);    }

    以该程序中的重载为例,此时相当于在堆底将要插入元素x,当这个函数返回true时,x才能够与堆底与之比较的元素交换,即x上浮。而A*搜索需要f按照升序排列。因此如上定义,切忌写反。

Code

#include<cstdio>#include<queue>#define s secondusing namespace std;typedef pair<int,int> pii;const int sm = 1e3+5;const int sn = 1e6+5;const int inf = 0x3f3f3f3f;int N,M,S,T,K,tot;int _to[sn],to[sn],_nxt[sn],nxt[sn];int _hd[sm],hd[sm],_w[sn],w[sn];int d[sm],vis[sm];struct Astar {    int g,f,id;    bool operator < (const Astar&x) const {        return (f!=x.f)?(x.f<f):(x.g<g);    }}t,q;priority_queue<Astar>Q;priority_queue<pii,vector<pii>,greater<pii> >Que;void read(int &x) {    char ch=getchar();x=0;    while(ch>'9'||ch<'0') ch=getchar();    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();}void Add(int u,int v,int c) {    to[++tot]=v,nxt[tot]=hd[u],hd[u]=tot,w[tot]=c;    _to[tot]=u,_nxt[tot]=_hd[v],_hd[v]=tot,_w[tot]=c;}void Dijkstra(int St) {    for(int i=1;i<=N;++i)        d[i]=inf,vis[i]=0;    pii t; d[St]=0;    Que.push(make_pair(d[St],St));    while(!Que.empty()) {        t=Que.top(),Que.pop();        if(vis[t.s]) continue;        vis[t.s]=1;        for(int i=_hd[t.s];i;i=_nxt[i])            if(!vis[_to[i]]&&d[t.s]+_w[i]<d[_to[i]]) {                d[_to[i]]=d[t.s]+_w[i];                Que.push(make_pair(d[_to[i]],_to[i]));            }    }}int A(int u,int v) {    int k=0;    while(!Q.empty()) Q.pop();    if(u==v) ++K;    q = (Astar){ 0,d[u],u };    Q.push(q);    while(!Q.empty()) {        t=Q.top(),Q.pop();        if(t.id==v) {            ++k;            if(k==K) return t.g;        }        for(int i=hd[t.id];i;i=nxt[i]) {            q=(Astar){ t.g+w[i],t.g+w[i]+d[to[i]],to[i] };            Q.push(q);        }       }    return -1;}int main() {    int u,v,c;    read(N),read(M);    for(int i=1;i<=M;++i) {        read(u),read(v),read(c);        Add(u,v,c);    }    read(S),read(T),read(K);    Dijkstra(T);    if(d[S]==inf) puts("-1");    else printf("%d\n",A(S,T));    return 0;}
阅读全文
0 0
原创粉丝点击