有负权值的求最短路

Description

N cities named with number 1 … N are connected with one-way roads. There are two kinds of road. You need to pay for the normal roads when you go through them, but for the special road, you can earn some money instead. You live in city 1 and your girl friend lives in city N, if you want to visit her, you need to calculate how much you need to pay.

Input

The first line contains two integers N, K and Q (2<=N<=100, 1<=K<=4000). N is the number of cities, K is the number of roads. Each of following K lines contains three integers i, j, d (1<=i,j<=N), indicates there is a road from city i to city j. d>=0 means this road is a normal road and costs d yuan, otherwise it means this road is a special road and you can earn -d yuan.

Output

If you need to spend money, print the money you need to pay in one line; if you don’t need to spend money you should print “0”; and if you can’t reach city N, you should print “-1”.

Sample Input

3 3
1 2 3
2 3 2
1 3 6

Sample Output

5

分析

这是一个边有权值的有向图,值得注意的是有负权值。题目的意思其实就是找最短路(包括计算负权值在内),所以我们应该用Bellman算法。

代码

#include <iostream>
using namespace std;

int n, k;
int dis[105];
int inf = 9999999;
const int MAXN = 101;
int dist[MAXN][MAXN];

struct edge{
	int u, v, w;
}e[4003];


bool bellman(int source){
	for (int i = 1; i <= n; i++){
		dis[i] = inf;
	}
	dis[source] = 0;
	for (int i = 1; i <= n - 1; i++){
		for (int j = 1; j <= k; j++){
			if (dis[e[j].u] + e[j].w < dis[e[j].v])
				dis[e[j].v] = dis[e[j].u] + e[j].w;
		}
	}
	int t = dis[n];
	for (int j = 1; j <= k; j++){
		if (dis[e[j].u] + e[j].w < dis[e[j].v]){
			dis[e[j].v] = dis[e[j].u] + e[j].w;
		}
	}
	if (t != dis[n])
		return true;
	return false;
}

int main(){

	cin >> n >> k;
	for (int i = 1; i <= k; i++){
		cin >> e[i].u >> e[i].v >> e[i].w;
	}
	bool t = bellman(1);

	if (t || dis[n] <= 0) {
		cout << 0 << endl;
	}
	else if (dis[n] == inf) {
		cout << -1 << endl;
	}
	else {
		cout << dis[n] << endl;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值