P5960 【模板】差分约束算法

题目链接:【模板】差分约束算法 - 洛谷

思路:

题目要求可行解即可,我们可以用最长路或者最短路来求,这里我选用最长路的方式来求一组最小值解,最长路的建边方式是由小到大建边

代码如下:

import sys
from collections import deque
inf = 1 << 31
N = 5010
M = 15010

h = [-1] * N
w = [0] * M
ne = [0] * M
e = [0] * M
idx = 0

dist = [-inf] * N  
st = [False] * N 
cnt = [0] * N

def add(a, b, c):
    global idx
    e[idx] = b
    w[idx] = c
    ne[idx] = h[a]
    h[a] = idx
    idx += 1

def spfa():
    q = deque()
    dist[0] = 0
    q.append(0)
    st[0] = True
    
    while q:        
        t = q.pop()  
        st[t] = False  
        
        i = h[t]
        while i != -1:
            j = e[i]
            if dist[j] < dist[t] + w[i]: 
                dist[j] = dist[t] + w[i]
                
                cnt[j] = cnt[t] + 1
                if cnt[j] >= n + 1: return False  
                
                if not st[j]:
                    st[j] = True
                    q.append(j)
            i = ne[i]
    return True
    
n, m = map(int, sys.stdin.readline().split())

for _ in range(m):
    a, b, c = map(int, sys.stdin.readline().split())
    add(a, b, -c)  # a - b <= c, a - c <= b

for i in range(1, n + 1): add(0, i, 0)
    
if not spfa(): print("NO") 
else:
    for i in range(1, n + 1): print(dist[i], end = ' ')

    
    
    

你可能感兴趣的:(算法笔记,算法,python)