关于判断负环的疑惑
查看原帖
关于判断负环的疑惑
817044
cjwdyzxfblzs楼主2023/7/23 17:31

我一开始这样判断的负环,只有 30pts30pts


bool spfa()
{
    memset(dist, 0x3f, sizeof(dist));
    st.reset();
    std::queue<int> q;
    q.push(0);
    st[0] = true;
    dist[0] = 0;
    int cnt = 0;
    while (!q.empty())
    {
        int t = q.front(); q.pop();
        st[t] = false;
        for (int i = hs[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                if (!st[j])
                {
                    st[j] = true;
                    cnt ++ ;
                    if (cnt >= n + 1) return true;
                    q.push(j);
                }
            }
        }
    }
    return false;
}


然后改成这样子就 ACAC 了,很好奇为什么第一种是错误的。


int cnt[N];
bool spfa()
{
    memset(dist, 0x3f, sizeof(dist));
    st.reset();
    std::queue<int> q;
    q.push(0);
    st[0] = true;
    dist[0] = 0;
    while (!q.empty())
    {
        int t = q.front(); q.pop();
        st[t] = false;
        for (int i = hs[t]; i != -1; 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;
                if (cnt[j] > n) return true;
                if (!st[j])
                {
                    st[j] = true;
                    q.push(j);
                }
            }
        }
    }
    return false;
}

2023/7/23 17:31
加载中...