大致题意 : 有n个小朋友, 给定一些条件,条件分为两种 :
第一种是A,B不超过一定距离
第二种是A,B不小于一定距离
通过这些条件给他们排列, 问1到n的最远距离.
思路 : 由条件可以通过差分约束系统转化为最短路有关问题(这里是求最远路)
第一类条件是 a-b<d可转化为d[a]<d[b]+d(注意是最远路的松弛操作)
第二类条件是a-b>d可转化为 d[b]<d[a] + (-d)
通过这两个转化建图, 用SPFA求最短路, 若出现负环则不能排列返回-1.
AC代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <iterator>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <iomanip>
using namespace std;
stringstream ss;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 1010, M = 1e5+10;
const int INF = 0x3f3f3f3f;
int n,ml,md;
int h[N],e[M],ne[M],w[M],idx;
int d[N],cnt[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int SPFA()
{
queue<int> q;
q.push(1);
st[1] = 1;
d[1] = 0;
while(q.size())
{
int t = q.front();
q.pop();
st[t] = 0;
for(int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if(d[j] > d[t] + w[i])
{
d[j] = d[t] + w[i];
cnt[j] = cnt[t] + 1;
if(cnt[j] >= n) return -1;
if(!st[j])
{
q.push(j);
st[j] = 1;
}
}
}
}
if(d[n] == INF) return -2;
else return d[n];
}
int main()
{
cin>>n>>ml>>md;
memset(h, -1, sizeof h);
memset(d, 0x3f, sizeof d);
while(ml -- )
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
while(md -- )
{
int a,b,c;
cin>>a>>b>>c;
add(b,a,-c);
}
cout<<SPFA();
}