zoukankan      html  css  js  c++  java
  • 1874畅通工程续(dijkstra算法)

    迷糊了好长时间,一开始有好多不理解的,到现在还没完全理清,不过比上午好多了,感觉不错,

    #include<iostream>
    #include<cstring>
    #include<algorithm>
    #include<queue>
    using namespace std;
    int n,m;
    const int maxn = 210;
    const int maxm = 2010;
    const int inf = 0x3f3f3f3f;
    typedef pair<int,int> pii;
    int v[maxm],next[maxm],w[maxm];
    int first[maxn],d[maxn],e;
    
    void init()
    {
        e =0;
        memset(first,-1,sizeof(first));
    }
    
    void add_edge(int a,int b,int c)
    {
        v[e] = b;
        next[e] =first[a];
        w[e] =c;
        first[a] = e++;
    }
    
    void dijkstra(int src)
    {
        priority_queue<pii,vector<pii>,greater<pii> >q;
        memset(d,-1,sizeof(d));
        d[src] = 0;
        q.push(make_pair(0,src));
        while(!q.empty())
        {
            //while(!q.empty()/*&&q.top().first>d[q.top().second]*/)
                //q.pop();
            //if(q.empty())break;
            int u = q.top().second;
            q.pop();
            for(int i = first[u];i!=-1;i= next[i])
            {
                if(d[v[i]]==-1||d[v[i]]>d[u]+w[i])
                {
                    d[v[i]] = d[u]+w[i];
                    q.push(make_pair(d[v[i]],v[i]));
                }
            }
        }
    }
    
    int main()
    {
        while(cin >> n>> m)
        {
            init();
            int a,b,c;
            for(int i =0;i < m;i++)
            {
    
                cin >> a>> b>> c;
                add_edge(a,b,c);
                add_edge(b,a,c);
    
            }
            int x,y;
            cin >> x>> y;
            dijkstra(x);
            if(d[y]!= inf)cout<< d[y]<< endl;
            else cout<< "-1"<< endl;
        }
        return 0;
    }
    

      

  • 相关阅读:
    A. Dreamoon and Stairs(Codeforces Round #272)
    bootstrap之UpdateStrings
    FZU
    IT忍者神龟之 oracle行转列、列转行
    linux find 10天内改动过的文件
    内核调试日志打印宏
    ack-grep 代码全文搜索
    JDK配置 linux
    IDA修改游戏
    curl 访问https问题
  • 原文地址:https://www.cnblogs.com/DUANZ/p/3876025.html
Copyright © 2011-2022 走看看