Dijkstra优先队列优化

https://ac.nowcoder.com/acm/contest/283/H

#include
#define maxn 100005
#define inf 0x3f3f3f3f
#define eps 1000000007
#define ll long long
using namespace std;
struct edge
{
    int from,to,dist;
    edge(int u,int v,int d):from(u),to(v),dist(d) {}
};
struct heapnode
{
    int d,u;
    bool operator <(const heapnode& rhs) const
    {
        return d>rhs.d;
    }
};
vector edges;
vector G[maxn];
bool done[maxn];
int d[maxn];
int n,m,s,t;
void dijkstra()
{
    priority_queue q;
    for(int i=1; i<=n; i++) d[i]=inf;
    d[s]=0;
    memset(done,0,sizeof(done));
    q.push((heapnode)
    {
        0,s
    });
    while(!q.empty())
    {
        heapnode x=q.top();
        q.pop();
        int u=x.u;
        if(done[u])  continue;
        done[u]=true;
        for(int i=0; id[u]+e.dist)
            {
                d[e.to]=d[u]+e.dist;
                q.push((heapnode)
                {
                    d[e.to],e.to
                });
            }
        }
    }
}
long long pow_mod(long long a, long long b, long long p) // 快速幂  a的b次方求余p
{
    long long  ret = 1;
    while(b)
    {
        if(b & 1) ret = (ret * a) % p;
        a = (a * a) % p;
        b >>= 1;
    }
    return ret;
}
int main()
{
    int i,ans,u,v;
    ll w;
    cin>>n>>m>>s>>t;
    while(m--)
    {
        scanf("%d%d%lld",&u,&v,&w);
        w=log2(w);
        edges.push_back(edge(u,v,w));
        G[u].push_back(edges.size()-1);
    }
    dijkstra();
    if(d[t]==inf)
    {
        cout<<-1<

优化的另一版本

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define INF  0x3f3f3f3f   //定义一个很大的数
struct Node
{
    int num,val;   //存放结点编号和到初始点的距离
} nod;
priority_queue qq;;   //优先从小到大
bool operator < (Node a,Node b)
{
    if(a.val == b.val) return a.num>b.num;
    return a.val>b.val;              //先出小
}
int book[100];  //检查这个点是否用过
int dis[100];     //到原点最短距离
int D[100][100];  //记录路径长度
int V,E;
int main()
{
    int a,b,d;
    while(cin>>V>>E && V&& E)  //输入顶点数和边数
    {
        while(!qq.empty()) qq.pop(); //清空
        memset(book,0,sizeof(book));
        memset(D,-1,sizeof(D));
        for(int i=0; i>a>>b>>d;
            D[a][b] = D[b][a] = d;
        }

        for(int i=2; i<=V; i++)
            dis[i]=INF;

        dis[1]=0;
        nod.num=1;
        nod.val=0;
        qq.push(nod);   //将起点放入队列
        while(!qq.empty())  //不为空时
        {

            for(int i=2; i<=V; i++)
            {
                if(D[qq.top().num][i] != -1  &&dis[i]>dis[qq.top().num] + D[qq.top().num][i])
                {

                    dis[i]=dis[qq.top().num] + D[qq.top().num][i];
                    nod.num=i;
                    nod.val=dis[i];
                    qq.push(nod);
                }
            }

            qq.pop();
        }

        for(int i=1; i<=V; i++)
        {
            cout<<"初始点到"<

 

 

你可能感兴趣的:(ACM最短路Dijkstra)