用邻接map 和队列实现的单源 Dijkstra最短路

/*************************************************************************
	> File Name: Dijkstra.cpp
	> Author:keson
	> Mail:keson@bupt.edu.cn
	> Created Time: 2014年12月07日 星期日 17时09分20秒
 ************************************************************************/

#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<queue>
#include<fstream>
using namespace std;

const int INIT_MAX=100;

struct Node
{
    multimap<int,Node*> adjMap;  //可能一个节点到另外节点的距离是相同的值
  //  bool known=false;
    int dist=INIT_MAX;         //定义不能到达的距离
    Node* path;
};



//计算从节点s为起始点,到其他点的最小距离
void dijkstra(Node *s)
{
    s->dist=0;
//    s->known=true;
    queue<Node*>q;
    q.push(s);
    while(!q.empty())
    {
        Node *v=q.front();
        for(auto &w:v->adjMap)        //查询邻接,map的first是邻接点的距离,second是指向邻接点的指针 
        if(v->dist+w.first<w.second->dist)            
        {

            w.second->dist=v->dist+w.first;
            w.second->path=v;
            q.push(w.second);
        }
        q.pop();
}
}






void inputMat(vector<vector<int>> &T,int row,int col)
{
    ifstream in;
    in.open("infile");             //打开邻接矩阵的文件
    int i,j;
    vector<int> vec2(col);
    int val;
    cin.clear();
    cout<<"Enter the adj:"<<endl;
    for(i=0;i<row;++i)
    {
        vec2.clear();
        for(j=0;j<col;++j)
        {
            in>>val;
            vec2.push_back(val);
        }
        T.push_back(vec2);
    }
}

void adjNode(Node &v1,Node *v2,int distance)
{
    v1.adjMap.insert(make_pair(distance,v2));
}

//根据邻接矩阵创建邻接表
void createAdjMap(vector<Node> &vec,vector<vector<int>> &T)
{
   for(int i=0;i<T.size();i++)
   {
       for(int j=0;j<T[0].size();j++)
         if(T[i][j]<100&&T[i][j]>0)
            adjNode(vec[i],&vec[j],T[i][j]);
   }
}

//v1到v2的最短距离
void shortest(Node &v1,Node &v2)
{
    dijkstra(&v1);
    cout<<v2.dist<<endl;
}
int main()
{
   cout<<"Enter the number of the Vertex: "<<endl;
   int N;
   cin>>N;
  vector<Node> vec(N);
   vector<vector<int>> mat;
   inputMat(mat,N,N);
    createAdjMap(vec,mat);

   shortest(vec[0],vec[1]);  //第一个节点到第二个节点的最短璐

    dijkstra(&vec[0]);

    for(auto &w:vec)
    cout<<w.dist<<endl;


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值