码迷,mamicode.com
首页 > 其他好文 > 详细

POJ2449 (k短路)

时间:2015-06-26 21:02:22      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;

#define maxn 2008
#define maxm 2000008
#define INF 2000000000

int lt[maxn],LT[maxn],sum=1,SUM=1;
int h[maxn];
int s,t,k,n,m;
bool pd[maxn];

struct line{
    int u,v,w,nt;
}eg[maxm],EG[maxm];

inline void add(int u,int v,int w){
    eg[++sum].u=u; eg[sum].v=v; eg[sum].w=w; eg[sum].nt=lt[u]; lt[u]=sum;
}
inline void ADD(int u,int v,int w){
    EG[++SUM].u=u; EG[SUM].v=v; EG[SUM].w=w; EG[SUM].nt=LT[u]; LT[u]=SUM;
}
inline void read(int &x){
    char ch;
    for (ch=getchar();ch<0||ch>9;ch=getchar()); x=ch-48;
    for (ch=getchar();ch>=0&&ch<=9;ch=getchar()) x=x*10+ch-48;
}

inline void spfa(){
    queue<int> Q;
    for (int i=1;i<=n;i++) h[i]=INF;
    memset(pd,0,sizeof(pd));
     h[t]=0; pd[t]=1; Q.push(t);
     while (!Q.empty()){
         int u=Q.front(); Q.pop();
         for (int i=LT[u];i;i=EG[i].nt){
             int v=EG[i].v;
             if (h[u]+EG[i].w<h[v]){
                 h[v]=h[u]+EG[i].w;
                 if (!pd[v]){
                     pd[v]=1;
                     Q.push(v);
                 }
             }
         }
         pd[u]=0;
     }
}

class node{
public:
    int f,g,u;
    bool operator<(const node& t) const{
        return f>t.f;
    }
    node(int a,int b,int c):f(a),g(b),u(c){}
    node(){}
};

int iQ[maxn];
inline int A_star(){
    priority_queue<node> Q;
    memset(iQ,0,sizeof(iQ));
    iQ[s]=0; Q.push(node(h[s],0,s));
    while (!Q.empty()){
        node cur=Q.top();
        //printf("%d %d %d %d\n",cur.f,cur.g,cur.u,iQ[t]);
        Q.pop();
        iQ[cur.u]++;
        if (iQ[t]==k) return cur.f;
        if (iQ[cur.u]>k) continue;

        for (int i=lt[cur.u];i;i=eg[i].nt){
            int v=eg[i].v;
            Q.push(node(h[v]+cur.g+eg[i].w,cur.g+eg[i].w,v));
        }
    }
    return -1;
}

inline int main(){
    //freopen("1.in","r",stdin);
    read(n); read(m);
    for (int i=1;i<=m;i++) {
        int u,v,w;
        read(u); read(v); read(w);
        add(u,v,w);
        ADD(v,u,w); 
    }
    read(s); read(t); read(k);
    if (s==t) k++;
    spfa();
    //for (int i=1;i<=n;i++) printf("%d ",h[i]);
    printf("%d\n",A_star());
    return 0;
}

 

POJ2449 (k短路)

标签:

原文地址:http://www.cnblogs.com/rpSebastian/p/4603209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!