bool bellman_ford(const vector<vector<pair<int, int> > > &adj, int sta, vector<int> &tab){
tab.resize(adj.size(), INT_MAX);
tab[sta] = 0;
for(size_t rou=1; rou<=adj.size(); rou++){ /// 总共进行adj.size()轮松弛操作
int cou = 0;
for(size_t nex=0; nex<adj.size(); nex++){ /// 枚举出所有的点
if(tab[nex] != INT_MAX){ /// 如果该点可达
for(auto &edg: adj[nex]){ /// 尝试以该点为中介,对其邻接的所有点进行松弛操作
if(tab[edg.second] > tab[nex]+edg.first){
tab[edg.second] = tab[nex]+edg.first;
if(rou == adj.size()){ /// 有定理:如果图内没有负环,那么到所有点的距离一定会在adj.size()-1轮松弛操作内全部松弛完毕
return false; /// 若adj.size()轮松弛时,仍然有距离可以松弛,说明图内一定有负环,返回假
}
cou++; /// 累计本轮松弛的次数
}
}
}
}
if(cou == 0){ /// 若本轮没有出现松弛,则说明所有距离已经松弛完毕
return true;
}
}
return true;
}
队列优化
bool bellman_ford(const vector<vector<pair<int, int> > > &adj, int sta, vector<int> &tab){
vector<bool> mas(adj.size(), false); /// 标记某点是否在队列中
vector<size_t> cou(adj.size(), 0); /// 累计某点进入队列的次数,即进行松弛操作的次数
tab.resize(adj.size(), INT_MAX);
tab[sta] = 0;
queue<int> que; /// 基于思想:若某点的距离出现松弛,其邻接的各点才有必要进行松弛
que.push(sta);
mas[sta] = true;
cou[sta]++;
while(!que.empty()){
int nex = que.front();
que.pop();
mas[nex] = false;
for(auto &edg: adj[nex]){
if(tab[edg.second] > tab[nex]+edg.first){
tab[edg.second] = tab[nex]+edg.first;
if(!mas[edg.second]){ /// 若该点不再队列中则将其加入队列
que.push(edg.second);
mas[edg.second] = true;
if(++cou[edg.second] == adj.size()){ /// 该点即将进行第adj.size()轮松弛,说明图内有负环
return false;
}
}
}
}
}
return true;
}