最短路径-Dijkstra

输入样例:

4 4 1
1 2 2
1 4 8
3 2 16
3 4 10
1

输出样例:

1->1:0
1->2:2
1->3:no path
1->4:8

 思路:

标题即思路,只需要熟记Dijkstra算法就可以把这道题做出来,关于Dijkstra算法网上的教程有很多,大家可以去学习一下。Dijkstra也算是PAT的一大考点,学会了Dijkstra最短路径就不怕了。

本题目的节点数比较少,用Floyd算法应该是可以通过的,但其实在实战中,Floyd一般都会超时,所以希望可以学习一下Dijkstra算法。

什么时候能独自写出Dijkstra算法,那么就算是学会了,所以千万不要觉得难,模板题都是万变不离其宗的。

参考代码:

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

int n, m, type;
const int MAXSIZE = 11;
const int INVALID = 2147483647;
int connect[MAXSIZE][MAXSIZE];

// 模板,只要能独立写一遍,差不多就会了,千万不要觉得难
void dijkstra(int start) {
    int consumes[MAXSIZE];
    bool searched[MAXSIZE];
    for(int i=1;i<=n;++i) {
        searched[i] = false;
        consumes[i] = connect[start][i];
    }
    searched[start] = true;
    consumes[start] = 0;
    while(true) {
        int minConsume = INVALID, minPoint = -1;
        for(int i=1;i<=n;++i) {
            if(!searched[i] && consumes[i] < minConsume) {
                minConsume = consumes[i];
                minPoint = i;
            }
        }
        if(minPoint == -1) break;
        searched[minPoint] = true;
        for(int i=1;i<=n;++i) {
            if(!searched[i] && connect[minPoint][i] != INVALID && connect[minPoint][i] + consumes[minPoint] < consumes[i]) {
                consumes[i] = connect[minPoint][i] + consumes[minPoint];
            }
        }
    }
    for(int i=1;i<=n;++i) {
        cout<<start<<"->"<<i<<":";
        if(consumes[i] != INVALID) {
            cout<<consumes[i]<<endl;
        } else {
            cout<<"no path"<<endl;
        }
    }
}


void init() {
    for(int i=0;i<MAXSIZE;++i) {
        for(int j=0;j<MAXSIZE;++j) {
            connect[i][j] = INVALID;
        }
    }
}

int main() {
    cin>>n>>m>>type;
    init();
    while(m--) {
        int from, to, distance;
        cin>>from>>to>>distance;
        connect[from][to] = distance;
        if(type == 0) {
            connect[to][from] = distance;
        }
    }
    int start;  cin>>start;
    dijkstra(start);
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「江太白」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值