【BZOJ 1598】 牛跑步

【题目链接】

           https://www.lydsy.com/JudgeOnline/problem.php?id=1598

【算法】

          A*求k短路

【代码】

          

#include<bits/stdc++.h>
using namespace std;
#define MAXN 1010
#define MAXM 10010
const int INF = 2e9;

int i,n,m,k,tot,rtot,u,v,w;
int head[MAXN],rhead[MAXN],dist[MAXN];

struct Edge
{
        int to,w,nxt;
} e[MAXM<<1];
struct info
{
        int s,d;
        friend bool operator < (info a,info b)
        {
                return a.d + dist[a.s] > b.d + dist[b.s];        
        }        
};

inline void add(int u,int v,int w)
{
        tot++;
        e[tot] = (Edge){v,w,head[u]};
        head[u] = tot;
        tot++;
        e[tot] = (Edge){u,w,rhead[v]};
        rhead[v] = tot;
}
inline void dijkstra(int s)
{
        int i,u,v,w;
        static bool visited[MAXN];
        priority_queue< pair<int,int> > q;
        while (!q.empty()) q.pop();
        memset(visited,false,sizeof(visited));
        for (i = 1; i <= n; i++) dist[i] = INF;
        dist[s] = 0;
        q.push(make_pair(0,s));
        while (!q.empty())    
        {
                u = q.top().second;
                q.pop();
                if (visited[u]) continue;
                visited[u] = true;
                for (i = rhead[u]; i; i = e[i].nxt)
                {
                        v = e[i].to;
                        w = e[i].w;
                        if (dist[u] + w < dist[v])
                        {
                                dist[v] = dist[u] + w;
                                q.push(make_pair(-dist[v],v));        
                        }        
                }    
        }    
}
inline void Astar(int s,int t)
{
        int i,v,w,cnt = 0;
        priority_queue< info > q;
        info cur;
        while (!q.empty()) q.pop();
        q.push((info){s,0});
        while (!q.empty())
        {
                cur = q.top();
                q.pop();
                if (cur.s == t)
                {
                        cnt++;
                        if (cnt <= k) printf("%d\n",cur.d);
                        else break;        
                }        
                for (i = head[cur.s]; i; i = e[i].nxt)
                {
                        v = e[i].to;
                        w = e[i].w;
                        q.push((info){v,cur.d+w});
                }
        }    
        for (i = 1; i <= k - cnt; i++) printf("-1\n");    
}

int main() 
{
        
        scanf("%d%d%d",&n,&m,&k);
        for (i = 1; i <= m; i++)
        {
                scanf("%d%d%d",&u,&v,&w);
                add(u,v,w);        
        }
        dijkstra(1);
        Astar(n,1);
        
        return 0;
    
}

猜你喜欢

转载自www.cnblogs.com/evenbao/p/9272258.html