package main
import"fmt"// bellman ford 算法计算单源点到其他点的距离,它无法处理含有负权回路的图funcmain(){type edge struct{
from, to, weight int}
graphs :=[]edge{{from:0, to:1, weight:6},{from:1, to:2, weight:-2},{from:0, to:2, weight:3},{from:2, to:3, weight:5},{from:3, to:1, weight:7},}
max :=0x3f3f3f3f
distance :=make([]int,len(graphs))
m :=len(graphs)// 边数, 暂时手动设置
n :=len(graphs)-1// 顶点数, 暂时手动设置for i :=0; i < n; i++{
distance[i]= max
}
distance[0]=0// 自己到自己的距离是0for i :=0; i < n; i++{for j :=0; j < m; j++{if distance[graphs[j].from]< max {
distance[graphs[j].to]=min(distance[graphs[j].to], distance[graphs[j].from]+graphs[j].weight)}}}
flag :=falsefor i :=0; i < n; i++{if distance[graphs[i].to]> distance[graphs[i].from]+graphs[i].weight {
flag =true}}if flag {
fmt.Println("含有负权回路")return}
fmt.Println(distance[:n])//return [0 6 3 8]}funcmin(a int, b int)int{if a < b {return a
}return b
}