题目
题解思路
难点在用差分约束的条件建图,今天才学了点差分约束。
结论 证明和有关差分约束的详解
我们只要将题目的条件不等式符号,全转化为<=号,然后跑最短路,如果存在负环就是不能到达的,如果最短路跑不过去,那就是无限大。
AC代码
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int const INF = 0x3f3f3f3f;
struct node
{
int z,w;
};
int dis[1010];
bool vis[1010];
int cnt[1010];
vector <node> head[1010];
int n,m1,m2;
void spfa()
{
for (int i = 1 ;i <= 1000 ; i++ )
dis[i] = INF ;
queue <int> q;
q.push(1);
dis[1] = 0;
vis[1] = 1;
cnt[1]++;
int tmp;
while(!q.empty())
{
tmp = q.front();
q.pop();
vis[tmp] = 0;
for ( int i = 0 ;i < head[tmp].size() ; i++ )
{
if ( dis[head[tmp][i].z] > dis[tmp] + head[tmp][i].w )
{
dis[head[tmp][i].z] = dis[tmp] + head[tmp][i].w;
if (cnt[head[tmp][i].z] > n )
{
cout<<"-1\n";
return ;
}
if (!vis[head[tmp][i].z])
{
vis[head[tmp][i].z] = 1;
cnt[head[tmp][i].z]++;
q.push(head[tmp][i].z);
}
}
}
}
if ( dis[n] == INF )
cout<<"-2\n";
else
cout<<dis[n]<<"\n";
}
int main ()
{
node tmm;
cin>>n>>m1>>m2;
for (int i = 1 ;i <= m1 ; i++ )
{
int a,b,c;
cin>>a>>b>>c;
tmm.z = b;
tmm.w = c;
head[a].push_back(tmm);
}
for (int i = 1 ;i <= m2 ; i++ )
{
int a,b,c;
cin>>a>>b>>c;
tmm.z = a;
tmm.w = -c;
head[b].push_back(tmm);
}
spfa();
return 0;
}