1129. 热浪 图论 单源最短路

题意重述

第一行输入点的数量,边的数量,起点和终点的标号。

第二行输入每条边的起终点以及每一条路的花费,除起终点外都是双向路

输出s到t最少的花费。

代码

用spfa

#include<bits/stdc++.h>
using namespace std;

const int N = 2000009, INF = 1e9;

struct node
{//node表示一条边 
    int to, w;
    //to表示路径终点,w表示路径权值
    bool operator <(const node &x) const
    {
        if(w == x.w) return to > x.to;
        else return w > x.w;
    }
};

bool v[N];//记录节点有没有被访问 
int d[N];//记录每一个节点到起点最短路 
int n;//节点个数
int m;//边的个数
int s, e;//起点与终点
vector <node> vec[N];
priority_queue <node> q;//优先队列 

void dijkstra(int x)
{
    for(int i = 1;i <= n;++ i) d[i] = INF, v[i] = false;
    //一开始,所有边都不与起点连通 
    d[x] = 0;//起点到自己的距离为0 
    q.push((node){x, 0});//起点入队 
    while(!q.empty())//当优先队列里还有变
    {
        node e = q.top(), tmp; q.pop();//
        v[e.to] = true;
        for(int i = 0;i < vec[e.to].size();++ i)
        {
            tmp = vec[e.to][i];
            if(v[tmp.to]) continue;
            if(d[tmp.to] > d[e.to] + tmp.w)
            {
                d[tmp.to] = d[e.to] + tmp.w;
            //  cout << e.to << " " << tmp.to << " " << d[tmp.to] << endl;
                q.push((node) {tmp.to, d[tmp.to]});
            }   
        }
    }

    return;
}

int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n >> m >> s >> e;
    for(int i = 1, u, v, w;i <= m;++ i)
    {//u代表路径起点,v代表路径终点,w代表路径长度 
        cin >> u >> v >> w;
        vec[u].push_back((node) {v, w});//建边 
        vec[v].push_back((node) {u, w});//建反边
        //因为是无向图,建两条边 
    }

    dijkstra(s);//从起点开始

    cout << d[e] << endl;//输出答案 

    return 0;
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值