算法训练 最短路 (spfa算法)

99 篇文章 0 订阅
95 篇文章 0 订阅


Link:点击打开链接


问题描述
给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。


输入格式
第一行两个整数n, m。


接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。


输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。
样例输入
3 3
1 2 -1
2 3 -1
3 1 2
样例输出
-1
-2
数据规模与约定
对于10%的数据,n = 2,m = 2。


对于30%的数据,n <= 5,m <= 10。


对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。



AC code:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<vector>
#define LL long long
#define EPS 1e-9
#define MAXN 200010
#define INF 9999999999
using namespace std;
struct node{
	int u,v,w;
	int next;
}E[MAXN];
bool hash[MAXN];
int head[MAXN];
LL dis[MAXN];//结果 
int tot,n,m;//n点个数  m边条数  
void init()
{
    memset(head,-1,sizeof(head));
	tot=0;
}
void ins(int uu,int vv,int ww)//前向星 
{
	E[tot].u=uu;
	E[tot].v=vv;
	E[tot].w=ww;
	E[tot].next=head[uu];
	head[uu]=tot++;
}
bool spfa(int s,int n)//s为源点 
{
	queue<int>que;
	int count[MAXN];
//	memset(dis,INF,sizeof(dis);wa
//	memset(hash,false,sizeof(hash));wa
//	memset(count,0,sizeof(count));wa
	for(int i=0;i<=n;i++)//切记:不能直接用上面的memset,必須确定范围,否则结果wa!!! 
	{
		dis[i]=INF;
		hash[i]=false;
		count[i]=0;
	}
	dis[s]=0;
	que.push(s);
	hash[s]=true;
	count[s]=1;
	while(!que.empty())
	{
		int u=que.front();
		que.pop();
		hash[u]=false;
		if(count[u]>n)//存在负环 
			return false;
		for(int i=head[u];i!=-1;i=E[i].next)
		{
			int v=E[i].v;
			if(dis[v]>dis[u]+E[i].w)
			{
				dis[v]=dis[u]+E[i].w;
				if(!hash[v])
				{
					que.push(v);
					hash[v]=true;
					count[v]++;
				}
			}
		}
	}
	return true;
 } 
int main()
{
	int u,v,w;
	while(cin>>n>>m)
	{
		init();
		for(int i=1;i<=m;i++)
		{
			cin>>u>>v>>w;
			ins(u,v,w);
		}
		spfa(1,n);
		for(int i=2;i<=n;i++)
		{
			cout<<dis[i]<<endl;
		} 
	}
	return 0;
 } 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

林下的码路

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

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

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

打赏作者

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

抵扣说明:

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

余额充值