zoukankan      html  css  js  c++  java
  • 最短路,dijstra算法

    #include<iostream>
    #include<stdio.h>
    #include<math.h>
    #include<vector>
    using namespace std;
    
    struct e{
        int next,c;
    };
    vector<e> edge[101];
    bool mark[101];
    int dis[101];
    
    int main (){
        int n,m;
        while (cin>>n>>m && n!=0 && m!=0){
            int a,b,c;
            e temp;
            //初始化 
            for (int i=1;i<=n;i++){
                edge[i].clear();
                dis[i]=-1;
                mark[i]=false;
            }
            dis[1]=0;
            mark[1]=true;
            
            
            while(m--){
                cin>>a>>b>>c;
                temp.c=c;
                temp.next=a;
                edge[b].push_back(temp);
                temp.next=b;
                edge[a].push_back(temp);
            }
            
            int newp=1;
            for (int i=1;i<n;i++){
                for (int j=0;j<edge[newp].size();j++){
                    int nex=edge[newp][j].next;
                    int c = edge[newp][j].c;
                    if (mark[nex] == true)
                    continue;
                    if (dis[nex]==-1 || dis[nex]>dis[newp]+c)//floyd也有若不可达或者比之小,不知道为啥要有不可达,先记住 
                    dis[nex] = dis[newp]+c;
                }
                int min=100000000;
                for (int j=1;j<=n;j++){
                    if (mark[j] == true)
                    continue;
                    if (dis[j] == -1)//因为我们的无穷大不是无穷,而是-1,之后的比大小有影响 
                    continue;       //所以要加上这个条件
                    if(dis[j]<min){
                        min = dis[j];
                        newp=j;
                    }  
                }
                mark[newp]=true;
                
                
            }
        cout<<dis[n]<<endl;
        }
    
        return 0;
    
    }

    在写代码上感觉比floyd麻烦很多。但是floyd是n的三次方的复杂度,被求解图的大小不能大于200个节点

    dijstra是n的平方的复杂度

    标红的邻接链表初始化我总是忘记

    核心代码循环n-1次,先更新通过新节点后的dis,再找更新后最近的成为newp

  • 相关阅读:
    有用工具
    Questions
    Verizon Wireless 4G LTE DROID
    测试的几点心得
    推荐书
    工作总结
    电脑故障排查检修积累
    Windows 8 下如何安装Framework 3.5
    空间域名的选择项
    自动化research
  • 原文地址:https://www.cnblogs.com/yexiaoqi/p/7236064.html
Copyright © 2011-2022 走看看