标签:pen ide map alt set next img hide view
void Add(int u,double cost,int v)//邻接表存储关系 { w[top] = cost; Key[top] = v; next[top] = head[u]; head[u] = top++; } bool SPFA(int x) { memset(vis,false,sizeof(vis)); memset(inq,0,sizeof(inq)); queue<int> Q; for(int i = 1;i <= n;i++) dis[i] = (i == x ? 0 : INF); vis[x] = true; inq[x] = 1; Q.push(x); while(!Q.empty()) { int cur = Q.front(); Q.pop(); vis[cur] = false; for(int e = head[cur] ; e != -1; e = next[e]) { int v = Key[e]; if(dis[v] < dis[cur] * w[e]) { dis[v] = dis[cur] * w[e]; if(!vis[v]) { inq[v] ++; if(inq[v] >= n) return true;//如果入队次数超过n-1次说明存在环或负权 Q.push(v); vis[v] = true; } } } } return false; }
初始map为INF
bool SPFA(int x) { queue<int> Q; memset(vis,false,sizeof(vis)); memset(in,false,sizeof(in)); for(int i = 1;i <= n;i++) dis[i] = (i==x?0: INF); vis[x] = true; Q.push(x); in[x] = 1; while(!Q.empty()) { int cur = Q.front(); Q.pop(); vis[cur] = false; for(int i = 1;i <=n;i++) { if(map[cur][i]!=-INF&&dis[i] < dis[cur] * map[cur][i]) { dis[i] = dis[cur] * map[cur][i]; if(!vis[i]) { in[i] ++; if(in[i] >= n) return true;//如果入队次数超过n-1次说明存在环或负权 Q.push(i); vis[i] = true; } } } } return false; }
标签:pen ide map alt set next img hide view
原文地址:https://www.cnblogs.com/DWVictor/p/10294754.html