dij的优先队列边表优化

dij的复杂度为v*v,通过优先队列优化后为e*logv.

(第一次写,没有过多的测试,不保证对。只当是测试blog了!)

#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct edge
{
    int v,w,next;
}e[20000];
typedef struct nd
{
    int dis,v;
    nd(int d,int vv){dis=d;v=vv;}
    bool operator<(const nd &b)const
    {
        return dis>b.dis;
    }
}cmpnode;
int head[1000]={0},js=0;
int dist[1000];
bool vis[1000];
priority_queue<cmpnode>q;
int n,m,s,t;
void addage(int u,int v,int w)
{
    e[++js].v=v;e[js].w=w;
    e[js].next=head[u];head[u]=js;
}
void dij(int st)
{
    dist[st]=0;
    q.push(cmpnode(0,st));
    while(!q.empty())
    {
        cmpnode tp=q.top();q.pop();
        if(tp.v==t)return;
        if(vis[tp.v])continue;
        vis[tp.v]=1;
        for(int i=head[tp.v];i;i=e[i].next)
        {
            int v=e[i].v,w=e[i].w;
            if(dist[v]>dist[tp.v]+w)dist[v]=dist[tp.v]+w;
            q.push(cmpnode(dist[v],v));
        }
    }
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        addage(a,b,c);
        addage(b,a,c);
    }
    cin>>s>>t;
    for(int i=0;i<1000;i++)dist[i]=0x7fffffff;
    dij(s);
    cout<<dist[t];
    return 0;
}

 

posted on 2016-08-24 20:45  gryzy  阅读(379)  评论(0编辑  收藏  举报

导航