1.求最大值,用最短路,不等式转化成 a <= b + c形式,从b向a建立权值为c的边g[b].append((a,c))
2.求最小值,用最长路,不等式转化成a >= b + c形式,从b向a建立权值为c的边
python
import sys
from collections import defaultdict, deque
from math import inf, sqrt
RI = lambda: int(sys.stdin.readline().strip())
RS = lambda: sys.stdin.readline().strip()
RII = lambda: map(int, sys.stdin.readline().strip().split())
RILIST = lambda: list(RII())
g = defaultdict(list)
n,ml,md = RII()
# 求最大值,用最短路,a <= b + c形式表示
# 按顺序排列,要求 i <= (i + 1) + 0
for i in range(1,n + 1):
g[i + 1].append((i,0))
# b - a <= l b <= a + l
for _ in range(ml):
a,b,l = RII()
if b < a:
a,b = b,a
g[a].append((b,l))
# b - a >= d a <= b - d
for _ in range(md):
a,b,d = RII()
if b < a:
a,b = b,a
g[b].append((a,-d))
dis = [inf]*(n + 1)
def spfa(k):
# 最短路,找负环
global dis
dis = [inf]*(n + 1)
cnt = [0]*(n + 1)
st = [0]*(n + 1)
q = deque()
for i in range(1,k + 1):
dis[i] = 0
st[i] = 1
q.append(i)
while q:
u = q.popleft()
st[u] = 0
for v,w in g[u]:
if dis[v] > dis[u] + w:
dis[v] = dis[u] + w
cnt[v] = cnt[u] + 1
if cnt[v] >= n:
return True
if not st[v]:
st[v] = 1
q.append(v)
return False
if spfa(n):
print(-1)
else:
spfa(1)
if dis[n] == inf:
print(-2)
else:
print(dis[n])