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;
}
}