解题思路:很标准的差分约束题目,根据题意列出不等式,并将所有的不等式转化为 ≤ 形式,然后跑最短路即可。
AC代码:
/*
* @Author: wchhlbt
* @Last Modified time: 2017-09-19
*/
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <limits>
#include <climits>
#include <cstdio>
#define Fori(x) for(int i=0;i<x;i++)
#define Forj(x) for(int j=0;j<x;j++)
#define maxn 10007
#define inf 0x3f3f3f3f
#define ONES(x) __builtin_popcount(x)
#define pb push_back
#define AA first
#define BB second
#define _ << " " <<
using namespace std;
typedef long long ll ;
const double eps =1e-8;
const int mod = 998244353;
const double PI = acos(-1.0);
int dx[5] = {0,0,1,-1,0};
int dy[5] = {1,-1,0,0,0};
inline int read(){ int cnt; scanf("%d",&cnt); return cnt;}
//每次使用前需要调用init函数初始化 可以处理负权边
//最坏复杂度O(V*E)
int d[maxn],inq[maxn];//inq数组储存当前点是否在队列中
int deg[maxn];//记录每个节点入队次数
vector<pair<int,int> > e[maxn]; //pair<节点, 边权>
int n;
void init()
{
for(int i = 0; i<maxn; i++){
e[i].clear();
d[i] = inf;
inq[i] = 0;
deg[i] = 0;
}
}
int SPFA(int s)//s为起点
{
queue<int> Q;
Q.push(s); d[s] = 0; inq[s] = 1; deg[s] = 1;
while(!Q.empty()){
int hd = Q.front();
Q.pop(); inq[hd] = 0;
for(int i = 0; i<e[hd].size(); i++){
int u = e[hd][i].first;
int v = e[hd][i].second;
if(d[u]>d[hd]+v){
d[u] = d[hd] + v;
if(inq[u]==1) continue;
inq[u] = 1;
deg[u]++;
if(deg[u]>=n) return -1;
Q.push(u);
}
}
}
if(d[n]==inf) return -2;
return d[n];
}
int main()
{
int x,y;
while(~scanf("%d%d%d",&n,&x,&y))
{
init();
for(int i = 0; i<x; i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
e[a].pb(make_pair(b,c));
//e[b].pb(make_pair(a,c));
}
for(int i = 0; i<y; i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
//e[a].pb(make_pair(b,-c));
e[b].pb(make_pair(a,-c));
}
cout << SPFA(1) << endl;
}
return 0;
}