ustbfym 2020-03-03
代码:
struct node{ int v, dis;//v为邻接边的目标顶点,dis为邻接边的边权 }; vector<node> Adj[MAXN]; int n; int d[MAXN]; bool Bellman_Ford(int s){ fill(d, d+MAXN; INF); d[s] = 0; for(int i = 0; i < n-1; i++){ for(int u = 0; u < n; u++){ for(int j = 0; j < Adj[u].size(); j++){ int v = Adj[u][j].v; int dis = Adj[u][j].dis; if(d[u] + dis < d[v]){ d[v] = d[u] + dis; } } } } //以下为判断负环的代码 for(int u = 0; u < n; u++){ for(int j = 0; j < Adj[u].size(); j++){ int v = Adj[u][j].v; int dis = Adj[u][j].dis; if(d[u] + dis < d[v]){ return false; } } } return true; }
struct node{ int v, dis;//v为邻接边的目标顶点,dis为邻接边的边权 }; vector<node> Adj[MAXN]; int n, d[MAXN], num[MAXN];//num数组为记录顶点入队列次数 bool inq[MAXV];//顶点是否在队列中 bool SPFA(int s){ //初始化 memset(inq, false, sizeof(inq)); memset(num, 0, sizeof(num)); fill(d, d+MAXN, INF); //源点入队列部分 queue<int> Q; Q.push(s); inq[s] = true; num[s]++; d[s] = 0; //主体部分 while(!Q.empty()){ int u = Q.front(); Q.pop(); inq[u] = false; //遍历u所有邻接边v for(int j = 0; j < Adj[u].size(); j++){ int v = Adj[u][j].v; int dis = Adj[u][j].dis; //松弛操作 if(d[u] + dis < d[v]){ d[v] = d[u] + dis; if(!inq[v]){ Q.push(v); inq[v] = true; num[v]++; if(num[v] >= n) return false; } } } } return true; }