题目连接:点击打开链接
又是一道最短路
因为边权值可能为负所以使用BellmanFOrd算法求解
算法即如下述代码描述
注意判断负环即可
#include <iostream>
#include <cstring>
using namespace std;
struct e{
int u, v;
int len;
};
e edge[20005];
int BellmanFord(int N, int E)
{
int D[1005];
for(int i=2; i<=N; ++i) D[i]=1<<20;
D[1] = 0;
for(int i=1; i<=N-1; ++i)
for(int j=1; j<=E; ++j)
if(D[edge[j].v]>D[edge[j].u]+edge[j].len)
D[edge[j].v] = D[edge[j].u]+edge[j].len;
int flag = 1; //负环判断
for(int j=1; j<=E; ++j)
if(D[edge[j].v]>D[edge[j].u]+edge[j].len)
{
flag = 0;
break;
}
if(flag) return D[N];
else return -1;
}
int main()
{
ios::sync_with_stdio(false);
int N, ML, MD;
while(cin>>N>>ML>>MD)
{
for(int i=1; i<=ML; ++i)
{
int r;
cin>>edge[i].u>>edge[i].v>>r;
edge[i].len = r;
}
for(int i=1; i<=MD; ++i)
{
int r;
cin>>edge[i+ML].v>>edge[i+ML].u>>r;
edge[i+ML].len = -1*r;
}
int temp = BellmanFord(N,ML+MD);
cout<<((temp==(1<<20))?-2:temp)<<endl;
}
return 0;
}