Challenge——spfa

Challenge

题目描述

wys和zerinf经常出题来虐Zhuyu。有一天, wys搞了一个有向图,每条边的长度都是1。 他想让Zhuyu求出点1到点 N 的最短路。

"水题啊。", Zhuyu这么说道。

所以zerinf把某些边的长度增加了1(也就是说,每条边的长度不是1就是2)。现在,可怜的Zhuyu要向你求助了。

输入格式

第1行,两个整数 N (1 ≤ N ≤ 10^5) 和 M (1 ≤ M ≤ 10^6), 点和边的数量。

第2到 M + 1行: 三个整数 Ui, Vi, Wi (1 ≤ Wi ≤ 2), 从点 Ui 到 Vi 长度为 Wi 的边。

输出格式

一个整数,表示点1到点N的最短路。数据保证至少存在一条路径。

样例输入1

3 3

1 2 1

2 3 1

1 3 2

样例输出1

2

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int n,m,v,u,pre[100002],w,dis[100002],cnt;
queue<int> q;
bool used[100002];
struct ed{
	int to,w,next;
}e[1000002];
void add(int u,int v,int w,int b){
	e[++cnt].to=v;
	e[cnt].next=pre[u];
	e[cnt].w=w;
	pre[u]=b;
}
int main(){
	memset(pre,-1,sizeof(pre));
	memset(dis,0x3f,sizeof(dis));
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++){
		scanf("%d%d%d",&u,&v,&w);
		add(u,v,w,i);
	}
	q.push(1);
	used[1]=1;
	dis[1]=0;
	while(!q.empty()){
		int now=q.front();//
		q.pop();
		used[now]=0;
		for(int i=pre[now];i!=-1;i=e[i].next ){//printf("%d\n",i);
			if(e[i].w+dis[now]<dis[e[i].to]){
				dis[e[i].to]=e[i].w+dis[now];
				if(!used[e[i].to]){
					used[e[i].to]=1;
					q.push(e[i].to);
				}
			}
		}
	}
	printf("%d\n",dis[n]);
}
/*
6 9
1 2 1
2 4 3
4 6 15
1 3 12
2 3 1
4 3 4
3 5 5
4 5 13
5 6 4

11
*/
相关推荐
Wo3Shi4七30 分钟前
双向队列
数据结构·算法·go
Wo3Shi4七34 分钟前
列表
数据结构·算法·go
Wo3Shi4七40 分钟前
链表
数据结构·算法·go
Wo3Shi4七1 小时前
数组
数据结构·算法·go
CoovallyAIHub1 小时前
YOLOv13都来了,目标检测还卷得动吗?别急,还有这些新方向!
深度学习·算法·计算机视觉
转转技术团队2 小时前
边学边做:图片识别技术的学习与应用
后端·算法
一块plus2 小时前
2025 年值得一玩的最佳 Web3 游戏
算法·设计模式·程序员
前端拿破轮2 小时前
不是吧不是吧,leetcode第一题我就做不出来?😭😭😭
后端·算法·leetcode
一块plus2 小时前
什么是去中心化 AI?区块链驱动智能的初学者指南
人工智能·后端·算法
Mr_Xuhhh2 小时前
网络基础(1)
c语言·开发语言·网络·c++·qt·算法