SPFA求负环

大佬的理解:

 总结一下下:

在求负环时,我们为什么可以认为无论dist[]数组内取任何数,即使数组内的值都不同也可以呢?

首先我们我们可以假设有多种输入样例,这就就可以保证数组内的值都不同。

在第一个样例中,dist[]内的元素值都为0,此时进入SPFA,使每个点都入队,在for循环中,只有边权小于0才能入队,开始循环遍历,当满足条件时我们就可以结束。

在第二个或第n个样例中,由于我们并没有初始化,那么我们的dist[]数组内的值也就不同,在我们开始for循环遍历时,可能会有一下情况:

 1.虫洞(模板题)

 直接判断有没有负环,有负环就可以YES

/*
负环: 一个有向图/无向图中 环路的边权和<0
因为是一个环,所以可以循环无限次,那么这些环上的点的距离就会变成-∞

求负环:
基于spfa
spfa 每入队一次 就相当于更新一次 如果入队>=n次 
在bellman_ford中 每更新一次 最短距离变小 但一个点的最短距离不可能变小n次
1 统计每个点入队的次数 如果某个点入队n次 
    说明存在负环
         ←o
        ↓ ↑
o→o→o...o→o  总共n个点,则对于点i到其他点最多n-1条边,入队n次说明包含n条让dist[i]变小的边 
            同时因为更新原则是加上第n条边后最短路权重变小
            所以第n条边是负的 则该路径一定存在负环
2 统计当前每个点的最短路中所包含的边数,如果某个点的最短路所包含的边数>=n
    说明存在负环
n条边 则一定有n+1个点 但我们总共就n个点 所以这条最短路上一定有环
            同时因为更新原则是加上第n条边后最短路权重变小
            所以第n条边是负的 则该路径一定存在负环

推荐第2种方法:
考虑:
当数据如 -1
        o←o
      -1↓ ↑-1
        o→o
        -1
如果用第一种方法 转完一圈之后每个点只入队一次,达到判定要求则需要转n圈
O(n^2)
如果用第二种方法 转完一圈之后就能达到判定要求
O(n)

还有一个问题:
负环不一定从起点走到
      4
     ↓ ↑
1→...2→3
解决方案:
将所有点入队的同时把所有点的距离初始化为0
q.push(node) for all_node
dist[node] = 0 for all_node
why 所有点入队? (结合虚拟源点建新图理解)
    1 虚拟源点0向所有点连一条长度是0的边构成一条新的图
      同时以虚拟源点0作为新图的起点
    2 原图中存在负环 == 新图中存在负环
      而新图里所有的负环一定能从虚拟源点出发走到
    3 那么我们对新图做spfa时就是把虚拟源点0加入queue
      而0 pop出来后队列会把所有原图的节点加入queue
why dist[node]=0? 
    1 有负环 == 做完spfa后 存在点i dist[i] = -∞
    2 赋的初值0也是有限值,做完spfa后都会变成-∞
    3 w[node]都是有限值 则必然要更新无限次(更新次数>=n)

最后来个玄学操作
spfa O(m) ~ O(nm)
       当spfa效率比较低的时候(一直结束不了的时候)
等价于 存在负环

可测量化:当所有点入队次数超过2n,我们就认为图中很大可能存在负环
*/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

const int N = 510, M = 5210;
int n, m1, m2;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
int cnt[N];
bool st[N];
void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx ++ ;
}
bool spfa()
{
    memset(dist, 0, sizeof dist);
    memset(cnt, 0, sizeof cnt);
    memset(st, 0, sizeof st);

    queue<int> q;
    for (int i = 1; i <= n; i ++ )
    {
        q.push(i);
        st[i] = true;
    }

    while(q.size())
    {
        int t = q.front();
        q.pop();
        st[t] = false;

        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                cnt[j] = cnt[t] + 1;//从t到j多了一条边w[t][j]
                if (cnt[j] >= n) return true;
                if (!st[j])
                {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }

    return false;
}

int main()
{
    int T;
    scanf("%d", &T);
    while (T -- )
    {
        cin >> n >> m1 >> m2;
        memset(h, -1, sizeof h);
        idx = 0;
        for (int i = 0; i < m1; i ++ )
        {
            int a, b, c;
            cin >> a >> b >> c;
            add(a, b, c), add(b, a, c);
        }
        for (int i = 0; i < m2; i ++ )
        {
            //虫洞 回到t秒前  时间time-t秒
            // 单向负边
            int a, b, c;
            cin >> a >> b >> c;
            add(a, b, -c);
        }

        if (spfa()) cout << "YES" << endl;
        else cout << "NO" << endl;
    }

    return 0;
}

作者:仅存老实人
链接:https://www.acwing.com/solution/content/20506/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

2.观光奶牛(二分)

 

 

#include <iostream>
#include <cstring>

using namespace std;

const int N = 1010, M = 5010;
const double eps = 1e-4;

int n, m;
int w_ver[N];
int h[N], e[M], w_edg[M], ne[M], idx;
double dist[N];
int cnt[N], q[N];
bool st[N];

void add(int a, int b, int c) {
    e[idx] = b, w_edg[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
bool check(double limit) {
    memset(dist, 0, sizeof dist);//也可以不更新
    memset(cnt, 0, sizeof cnt);
    memset(st, 0, sizeof st);

    int hh = 0, tt = 0;
    for (int i = 1; i <= n; ++i) {
        q[tt++] = i;
        st[i] = true;
    }

    while (tt != hh) {
        int t = q[hh++];
        if (hh == N) hh = 0;
        st[t] = false;

        for (int i = h[t]; ~i; i = ne[i]) {
            int j = e[i];
            //这里求是否存在正环,因此spfa从寻找“最短路”改为寻找“最长路”
            if (dist[j] < dist[t] + w_ver[t] - limit * w_edg[i]) {
                dist[j] = dist[t] + w_ver[t] - limit * w_edg[i];
                cnt[j] = cnt[t] + 1;

                if (cnt[j] >= n) return true;

                if (!st[j]) {
                    st[j] = true;
                    q[tt++] = j;
                    if (tt == N) tt = 0;
                }
            }
        }
    }
    return false;
}
int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) scanf("%d", &w_ver[i]);

    memset(h, -1, sizeof h);
    while (m--) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }

    double l = 1, r = 1000;
    while (r - l > eps) {
        double mid = (l + r) / 2;
        if (check(mid)) l = mid;
        else r = mid;
    }
    printf("%.2lf\n", l);
    return 0;
}

作者:一只野生彩色铅笔
链接:https://www.acwing.com/solution/content/37185/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

3.单词环(二分+经验判断)

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 700, M = 100010;

int n;
int h[N], e[M], w[M], ne[M], idx;
double dist[N];
int q[N], cnt[N];
bool st[N];

void add(int a, int b, int c) {
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

bool check(double mid) {
    memset(st, 0, sizeof(st));
    memset(cnt, 0, sizeof(cnt));
    int hh = 0, tt = 0;
    for (int i = 0; i < 676; i++) {
        q[tt++] = i;
        st[i] = true;
    }
    int count = 0;
    while (hh != tt) {
        int t = q[hh++];
        if (hh == N) hh = 0;
        st[t] = false;
        for (int i = h[t]; i != -1; i = ne[i]) {
            int j = e[i];
             if (dist[j] < dist[t] + w[i] - mid) {
                 dist[j] = dist[t] + w[i] - mid;
                 cnt[j] = cnt[t] + 1;
                 if (++count > 10000) return true;
                 if (cnt[j] >= N) return true;
                 if (!st[j]) {
                     q[tt++] = j;
                     if (tt == N) tt = 0;
                     st[j] = true;
                 }
             }
        }
    }
    return false;
}

int main() {
    char str[1010];
    while (scanf("%d", &n)) {
        if (n == 0) break;
        memset(h, -1, sizeof(h));
        idx = 0;
        for (int i = 0; i < n; i++) {
            scanf("%s", str);
            int len = strlen(str);
            if (len >= 2) {
                int left = (str[0] - 'a') * 26 + str[1] - 'a',
                    right = (str[len - 2] - 'a') * 26 + str[len - 1] - 'a';
                add(left, right, len);
            }
        }
        if (!check(0)) puts("No solution");
        else {
            double l = 0, r = 1000;
            while (r - l > 1e-4) {
                double mid = (l + r) / 2;
                if (check(mid)) l = mid;
                else r = mid;
            }
            printf("%lf\n", r);
        }
    }
    return 0;
}

作者:lew2018
链接:https://www.acwing.com/solution/content/17712/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值