【最短路】CODE[VS] 1557 热浪 (Dijkstra模板)

拒绝前往德克萨斯州

哼唧


Dijkstra才是真正优美的最短路算法,不服来辩!

基本策略是贪心,正因为此性质,我们可以用一个小根堆维护,每次从堆定取出一个最小的

代码(+heap优化)

#include 
#include 
#include 
#include 
#include 
#include 

const int maxn = 200005;

using namespace std;

int tot;
int t,c,ts,te;
int head[maxn];
int dist[maxn];
bool used[maxn];

struct edge{
    int f,t,c,next;
}es[maxn << 1];

struct node{
    int u,v;
    bool operator < (const node &a)const
    {
        return v > a.v;
    }
};

inline void build(int x,int y,int z)
{
    tot++;
    es[tot].f = x;
    es[tot].t = y;
    es[tot].c = z;
    es[tot].next = head[x];
    head[x] = tot;
}

inline void rd(int &x)
{
    scanf("%d",&x);
}

inline void init()
{
    memset(head,0,sizeof(head));
    memset(used,0,sizeof(used));
    tot = 0;
    return ;
}

priority_queueq;

inline void dijkstra(int ss,int ee)
{
    memset(dist,108,sizeof(dist));
    dist[ss] = 0;
    q.push((node){ss,0});
    while(!q.empty())
    {   
        node now = q.top();
        int u = now.u;
        q.pop();
        if(used[u] == true) continue;
        used[u] = true;
        if(u == ee) return ;
        for(int i = head[u];i;i = es[i].next) 
        {
            int v = es[i].t;
            if(dist[v] > dist[u]+es[i].c)
            {
                dist[v] = dist[u]+es[i].c;
                q.push((node){v,dist[v]});
            }           
        }
    }
}

int main()
{
    init();
    rd(t);rd(c);rd(ts);rd(te);
    for(int i = 1;i <= c;i++)
    {
        int x,y,z;
        rd(x);rd(y);rd(z);
        build(x,y,z);
        build(y,x,z);
    }
    dijkstra(ts,te);
    printf("%d\n",dist[te]);

return 0;
}

THE END

By Peacefuldoge

http://blog.csdn.net/loi_peacefuldog

你可能感兴趣的:(【NOIP2016】,【图论-最短路问题】,【模板】,【贪心】,【优化-数据结构优化】)