zoukankan      html  css  js  c++  java
  • Dijkstra+优先队列

    /*
    Dijkstra的算法思想:
    在所有没有访问过的结点中选出dis(s,x)值最小的x
    对从x出发的所有边(x,y),更新
    dis(s,y)=min(dis(s,y),dis(s,x)+dis(x,y))
    */
    #include <iostream>
    #include <cstdio>
    #include <queue>
    #include <vector>
    using namespace std;
    const int Ni = 10000;
    const int INF = 1<<27;
    struct node
    {
        int x,d;
        node() {}
        node(int a,int b)
        {
            x=a;
            d=b;
        }
        bool operator < (const node & a) const
        {
            if(d==a.d) return x<a.x;
            else return d > a.d;
        }
    };
    vector<node> eg[Ni];
    int dis[Ni],n;
    void Dijkstra(int s)
    {
        int i;
        for(i=0; i<=n; i++) dis[i]=INF;
        dis[s]=0;
    //用优先队列优化
        priority_queue<node> q;
        q.push(node(s,dis[s]));
        while(!q.empty())
        {
            node x=q.top();
            q.pop();
            for(i=0; i<eg[x.x].size(); i++)
            {
                node y=eg[x.x][i];
                if(dis[y.x]>x.d+y.d)
                {
                    dis[y.x]=x.d+y.d;
                    q.push(node(y.x,dis[y.x]));
                }
            }
        }
    }
    int main()
    {
        int a,b,d,m;
        while(scanf("%d%d",&n,&m),n+m)
        {
            for(int i=0; i<=n; i++) eg[i].clear();
            while(m--)
            {
                scanf("%d%d%d",&a,&b,&d);
                eg[a].push_back(node(b,d));
                eg[b].push_back(node(a,d));
            }
            Dijkstra(1);
            printf("%d
    ",dis[n]);
        }
        return 0;
    }
    /*
    6 6
    1 2 2
    3 2 4
    1 4 5
    2 5 2
    3 6 3
    5 6 3
    */
  • 相关阅读:
    POJ3667 Hotel 题解
    POJ1417 True Liars 题解
    POJ2482 Stars in Your Window 题解
    POJ1704 Georgia and Bob 题解
    矩阵运算
    P4778 Counting Swaps 题解
    poi解析office文档内容的工具类
    VMware安装Centos7超详细过程(图文)
    java后端树形菜单结构
    vue点击事件的修饰符
  • 原文地址:https://www.cnblogs.com/yuanbo123/p/6798211.html
Copyright © 2011-2022 走看看