思路:比较裸的差分约束,直接建图然后spfa就可以了
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
#define inf 1e9
int d[maxn];
int inq[maxn];
int cnt[maxn];
int n,x,y;
vector<pair<int,int> >e[maxn];
int spfa()
{
memset(inq,0,sizeof(inq));
queue<int>q;
q.push(1);
d[1]=0;
inq[1]=1;
while(!q.empty())
{
int u = q.front();
q.pop();
inq[u]=0;
for(int i = 0;i<e[u].size();i++)
{
int v = e[u][i].first;
if(d[v]>d[u]+e[u][i].second)
{
d[v]=d[u]+e[u][i].second;
if(!inq[v])
{
inq[v]=1;
q.push(v);
if(++cnt[v]>n)
return -1;
}
}
}
}
return d[n];
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&n,&x,&y);
for(int i = 0;i<=n;i++)
d[i]=inf,e[i].clear(),cnt[i]=0;
for(int i = 1;i<=x;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
e[u].push_back(make_pair(v,w));
}
for(int i = 1;i<=y;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
e[v].push_back(make_pair(u,-w));
}
for(int i = 1;i<n;i++)
{
e[i+1].push_back(make_pair(i,0));
// e[i+1].push_back(make_pair(i,-1));
}
int ans = spfa();
if(ans==-1)
printf("-1\n");
else if(ans==inf)
printf("-2\n");
else
printf("%d\n",ans);
}
}