题目链接:点我啊╭(╯^╰)╮
题目大意:
头牛、按编号排队, 对牛的距离不能超过 、 对牛的距离不能小于 ,问 号牛到 号牛的距离最大是多少???
解题思路:
差分约束思想,下面简单介绍一下:
那么、不等式
和
相加得到:
要求
与
的最大差值,就是
,也就转化为了最短路的思想
同样,若给出
,则转换为
, 一个道理
代码思路:
判断一下负环即可
核心:差分约束的思想
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1010;
const int MAXM = 20010;
const int ANS_MAX = 1<<30;
struct EDGE {
int next;
int to;
ll w;
} edge[MAXM];
int n, m, st, cnt;
int head[MAXN], num[MAXN];
ll dis[MAXN];
bool vis[MAXN];
queue<int> Q;
inline int Read() { //读入优化 可忽略
char c;
int ans = 0;
bool Sign = false;
while(!isdigit(c=getchar()) && c != '-');
if(c == '-') {
Sign = true;
c = getchar();
}
do {
ans = (ans<<3) + (ans<<1) + (c - '0');
} while(isdigit(c=getchar()));
return Sign ? -ans : ans;
}
void Add(int u, int v, ll w) {
edge[++cnt].next = head[u];
edge[cnt].to = v;
edge[cnt].w = w;
head[u] = cnt;
}
void read() {
int x, y, ml, md;
ll w;
n = Read();
ml = Read();
md = Read();
for(int i=1; i<=ml; i++) {
x = Read();
y = Read();
w = Read();
Add(x, y, w);
}
for(int i=1; i<=md; i++) {
x = Read();
y = Read();
w = Read();
Add(y, x, -w);
}
}
bool SPFA(int x) {
while(!Q.empty()) Q.pop();
for(int i=1; i<=n; i++) dis[i] = ANS_MAX;
dis[x] = 0;
num[x] = 1;
Q.push(x);
vis[x] = true;
while(!Q.empty()) {
int k = Q.front();
Q.pop();
vis[k] = false;
if(dis[k] == ANS_MAX) continue;
for(int i=head[k]; i!=0; i=edge[i].next) {
int j = edge[i].to;
if(dis[j] > dis[k] + edge[i].w) {
dis[j] = dis[k] + edge[i].w;
num[j] = num[k]+1;
if(num[j]>n) return 1; //判断负环
if(!vis[j]) {
Q.push(j);
vis[j] = true;
}
}
}
}
return 0;
}
int main() {
memset(vis, 0, sizeof(vis));
memset(num, 0, sizeof(num));
memset(head, 0, sizeof(head));
cnt = 0;
read();
if(SPFA(1)) printf("-1\n");
else if(dis[n]==ANS_MAX) printf("-2\n");
else printf("%d\n", dis[n]);
}