负边权最短路

负边权

Bellman ford

接下来看几道栗子

给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数

请你求出从 1 号点到 n 号点的最多经过 k 条边的最短距离,如果无法从 1 号点走到 n 号点,输出 impossible

注意:图中可能 存在负权回路

输入格式

第一行包含三个整数 n,m,k

接下来 m 行,每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。

输出格式

输出一个整数,表示从 1 号点到 n 号点的最多经过 k 条边的最短距离。

如果不存在满足条件的路径,则输出 impossible

数据范围

1≤n,k≤500
1≤m≤10000
任意边长的绝对值不超过 10000。

输入样例:

3 3 1
1 2 1
2 3 1
1 3 3

输出样例:

3
#include<bits/stdc++.h>

using namespace std;

const int N = 1e4 + 10;

int dist[N];
int last[N];

struct node
{
	int x,y,z;
}no[N];

void bellman_ford(int k,int m)
{
	memset(dist,0x3f,sizeof dist);

	dist[1]=0;

	for(int i = 1; i<=k; i++)
	{
		memcpy(last,dist,sizeof dist);
		for(int j = 1; j<=m; j++)
		{
			dist[no[j].y]=min(dist[no[j].y],last[no[j].x]+no[j].z);
		}
	}
}

void solve()
{
	int n,m,k;

	cin >> n >> m >> k;

	for(int i = 1; i<=m; i++) cin >> no[i].x >> no[i].y >> no[i].z;
	
	bellman_ford(k,m);

	if(dist[n]==0x3f3f3f3f) cout <<"impossible"<<endl;
	else cout << dist[n] <<endl;
}

signed main()
{
	solve();

	return 0;
}

spfa

spfa是bellman ford的优化版

给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数

请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 impossible

数据保证不存在负权回路。

输入格式

第一行包含整数 n 和 m。

接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。

输出格式

输出一个整数,表示 1 号点到 n 号点的最短距离。

如果路径不存在,则输出 impossible

数据范围

1≤n,m≤10^5
图中涉及边长绝对值均不超过 10000

输入样例:

3 3
1 2 5
2 3 -3
1 3 4

输出样例:

2
#include<bits/stdc++.h>

using namespace std;

const int N = 1e4 + 10;

typedef pair<int,int>PII;

int dist[N];
bool st[N];
int q[N],hh,tt=-1;
vector<PII>g[N];

int spfa(int n)
{
	memset(dist,0x3f,sizeof dist);
	dist[1]=0;

	q[++tt]=1;
	st[1]=true;

	while(hh<=tt)
	{
		int t = q[hh++];

		st[t]=false;

		for(int i = 0; i<g[t].size(); i++)
		{
			int no = g[t][i].first;

			if(dist[no]>dist[t]+g[t][i].second)
			{
				dist[no]=dist[t]+g[t][i].second;
				if(!st[no])
				{
					q[++tt]=no;
					st[no]=true;
				}
			}
		}
	}

	return dist[n];
}

void solve()
{
	int n,m;

	cin >> n >> m;

	for(int i = 1; i<=m; i++)
	{
		int x,y,z;
		cin >> x >> y >> z;

		g[x].push_back({y,z});
	}

	int t = spfa(n);

	if(t==0x3f3f3f3f) cout <<"impossible" <<endl;
	else cout << t <<endl;
}

signed main()
{
	solve();

	return 0;
}
posted @   人间客,  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示