zoukankan      html  css  js  c++  java
  • Dijkstra

    /*

    O(V^2)

    */

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    using namespace std;

    int v,e;//顶点数
    const int INF=1<<30;
    const int max_v=1e4+5;
    int d[max_v];//顶点s出发的最短距离
    int cost[max_v][max_v];//边权值
    bool used[max_v];//已经使用过的图

    void  dijkstra(int start)
    {
        fill(d,d+v,INF);
        fill(used,used+v,false);
        d[start]=0;
        while(true)
        {
            int t=-1;
            for(int u=0;u<v;u++)
            {
                if(!used[u]&&(t==-1||d[u]<d[t]))
                    t=u;
            }
            if(t==-1)
                break;
            used[t]=true;
            for(int u=1;u<v;u++)
            {
                d[u]=min(d[u],d[t]+cost[t][u]);
            }

        }
    }

    int main()
    {
        cin>>v>>e;
        for(int i=0;i<v;i++)
        {
            for(int j=0;j<v;j++)
                cost[i][j]=INF;
        }
        int x,y,val;
        for(int i=0;i<e;i++)
        {
            cin>>x>>y>>val;
            cost[x][y]=val;
        }
        int start,End;
        cin>>start>>End;
        dijkstra(start);
        for(int i=0;i<v;i++)
            cout<<d[i]<<' ';
        cout<<endl;
        cout<< d[End]<<endl;
        return 0;
    }

  • 相关阅读:
    PHP常见问题总结
    Java常见问题总结(二)
    C语言常见问题总结
    C#常见问题总结(三)
    C#常见问题总结(二)
    Android常见问题总结(二)
    日期和时间类函数
    Eclipse开发工具介绍
    JavaScript中逻辑运算符的使用
    多路开关模式的switch语句
  • 原文地址:https://www.cnblogs.com/unknownname/p/7754310.html
Copyright © 2011-2022 走看看