SPFA模板
不能处理有环的图
void SPFA() { memset(vis, false, sizeof(vis)); vis[1] = true; for(int i = 1; i <= n; i++){ d[i] = cnt[i] = INF; } d[1] = cnt[1] = 0; while(!q.empty()) q.pop(); q.push(1); while(!q.empty()){ int u = q.front(); q.pop(); vis[u] = false;//入队的点开始不能确定是最优的 for(int i = 0; i < G[u].size(); i++){ int v = G[u][i].v, w = G[u][i].w; if(d[v] > d[u] + w){ d[v] = d[u] + w; if(!vis[v]){ vis[v] = true; q.push(v); } } } } printf("%d\n", d[n]); }