poj 2449 Remmarguts' Date 求第k短路 Astar算法

2021-07-02 02:05

阅读:396

标签:stdin   name   star   sizeof   dde   front   set   return   astar   

=.=好菜

#include 
#include 
#include string.h>
#include 
#include using namespace std;
const int N = 1e3+10;
const int M = 100000+10;
typedef long long ll;
const ll INF = 1e15;

int n,m,head[N],rehead[N],tot;
struct node {
    int v,w,next;
}E[M],reE[M];

void init() {
    tot=0;
    memset(head,0,sizeof(head));
    memset(rehead,0,sizeof(rehead));
}
void addEdge(int u,int v,int w) {
    ++tot;
    E[tot].next = head[u];
    head[u]=tot;
    E[tot].v = v;
    E[tot].w = w;

    reE[tot].next = rehead[v];
    rehead[v]=tot;
    reE[tot].v = u;
    reE[tot].w = w;
}

bool inq[N]; ll d[N];
queueint>que;
void spfa(int src) {
    while(!que.empty())
        que.pop();
    for(int i=0;iINF;
    memset(inq,0,sizeof(inq));
    d[src]=0;
    inq[src] = 1;
    que.push(src);
    while(!que.empty()) {
        int now = que.front();
        que.pop();
        //if(vis[now]) continue;
        //vis[now]=1;
        inq[now] = 0;
        for(int i=rehead[now]; i; i=reE[i].next) {
            int v = reE[i].v;
            int w = reE[i].w;
            if(d[v] > d[now] + w) {
                d[v] = d[now] + w;
                if(!inq[v])
                    que.push(v);
            }
        }
    }
}

struct A {
    int v;
    ll f,g;
    ///v是current点 f(v)=g(v)+h(v) g(v):st到v的估值, h(v):v到ed的估值
    bool operatorconst A other) const {
        if(other.f == f) return other.g  g;
        return other.f  f;
    }
};

int Astar(int st,int ed,int k) {
    priority_queue Q;
    if(st==ed) k++;
    if(d[st]==INF) return -1;
    int cnt = 0;
    A t,tt;
    t.v=st,t.g=0,t.f=t.g+d[st];
    Q.push(t);
    while (!Q.empty()) {
        tt = Q.top(); Q.pop();
        int u=tt.v;
        if(u == ed) {
            cnt++;
            if(cnt==k) return tt.g;
        }
        for(int i=head[u]; i; i=E[i].next) {
            t.v = E[i].v;
            t.g = tt.g + E[i].w;
            t.f = t.g + d[t.v];
            Q.push(t);

        }
    }
    return -1;
}


int main () {
    //freopen("in.txt","r",stdin);
    while (scanf("%d %d", &n, &m)==2) {
        init();
        for(int i=1;i) {
            int x,y,z; scanf("%d%d%d",&x,&y,&z);
            addEdge(x,y,z);
        }
        int s,t,k; scanf("%d%d%d",&s, &t, &k);
        spfa(t);
        //for(int i=1;i
        coutendl;
    }
    return 0;
}

 

poj 2449 Remmarguts' Date 求第k短路 Astar算法

标签:stdin   name   star   sizeof   dde   front   set   return   astar   

原文地址:https://www.cnblogs.com/Draymonder/p/9634958.html


评论


亲,登录后才可以留言!