经典例题

有边数限制的最短路

折叠代码块
 
#include 
using namespace std;
//
const int maxn = 505;
const int maxm = 10005;
const int inf = 0x3f3f3f3f;
//
int n = 0, m = 0, k = 0;
int dis[maxn] = {}, backup[maxn] = {};
//bellman_ford算法,只要能遍历所有边即可
struct edge	
{
	int a, b, w;
}e[maxm];
//
int bellman_ford()
{
	memset(dis, 0x3f, sizeof(dis));
	dis[1] = 0;
	//
	//最多经过k条边
	for(int i=1; i<=k; i++)
	{
		memcpy(backup, dis, sizeof(dis));
		for(int j=1; j<=m; j++)
		{
			int a = e[j].a, b = e[j].b, w = e[j].w;
			if(dis[b] > backup[a] + w) dis[b] = backup[a] + w;
		}
	}
	//
	if(dis[n] > inf / 2) return -inf;
	return dis[n];
}
//
int main()
{	
	scanf("%d%d%d", &n, &m, &k);
	for(int i=1; i<=m; i++)
	{
		scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].w);
	}
//
	int ans = bellman_ford();
	if(ans == -inf) printf("impossible");
	else printf("%d", ans);
	//
	return 0;
}
  
posted @ 2024-01-11 20:41  毛竹259  阅读(59)  评论(0编辑  收藏  举报