Dijkstra(邻接表实现)

 

#include<iostream>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
#define INF 0x3f3f3f3f
#define Max_N 1000
struct edge{int to,cost;};
typedef pair<int,int> P;  //first为到S最短距离,second为顶点编号

int V,E;
vector<edge> G[Max_N];  //每个G[v]里面包含一个边的edge类型vector,记录与顶点v相连的点和他们组成边的权值
int d[Max_N];

void dijkstra(int s)
{
    //创造优先队列que
    priority_queue<P,vector<P>,greater<P> > que;//最后两个>间有同一个空格,对于pair的P,默认first为排序依据
    fill(d,d+V,INF);
    d[s]=0;
    que.push(P(0,s));

    while(!que.empty())
    {
        P p=que.top();
        que.pop();
        int v=p.second;
        if(d[v]<p.first) continue;  //原来的值更小,不更新,跳过
        for(int i=0;i<G[v].size();i++)   //遍历与顶点v相连的边
        {
            edge e=G[v][i];
            if(d[e.to]>d[v]+e.cost)
            {
                d[e.to]=d[v]+e.cost;
                que.push(P(d[e.to],e.to));
            }
        }
    }
}
int main()
{
    //freopen("dijkstra.txt","r",stdin);
    //录入有向权图,起点S默认为第一个录入顶点
    cin>>V>>E;
    for(int i=0;i<E;i++)
    {
        int s,t,co;  //s为起点,t为终点,co为权
        cin>>s>>t>>co;
        G[s].push_back({t,co});
    }
    //
    dijkstra(0);
    for(int i=1;i<V;i++)
        cout<<"S到序号"<<i<<"顶点的最短距离:"<<d[i]<<endl;

}

 

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值