kuangbin 专题四:最短路练习 Til the Cows Come Home

题目链接:
传送门

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 2010;
//g为邻接矩阵,d为当前点到其他点的最短距离
int g[N][N], d[N], n, m;
//标记当前点是否已经是最短的了
bool checked[N];

//迪杰斯特拉算法模板
int dijkstra() {
	memset(d, 0x3f, sizeof(d));
	d[1] = 0;
	for(int i = 0; i < n; i++) {
		int t = -1;
		for(int j = 1; j <= n; j++)
			if(!checked[j] && (t == -1 || d[t] > d[j]))
				t = j;
		checked[t] = 1;
		for(int j = 1; j <= n; j++) {
			d[j] = min(d[j],d[t] + g[t][j]);
		}
	}
	if(d[n] == 0x3f3f3f3f) return -1;
	else return d[n];
}


int main()
{
    scanf("%d%d", &m, &n);
    //把邻接矩阵初始化
    memset(g, 0x3f, sizeof g);
    while (m--)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        //这里防一手重复边(不写min没给过)
        g[a][b] = min(g[a][b], c);
		g[b][a] = min(g[b][a], c);
    }
    printf("%d\n", dijkstra());
    return 0;
}

这是一道单源最短路径的模板题,直接套版做就好了,在输入时加个判断防止多次输入。
具体关于该算法的介绍请见:某大佬博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值