Problems of detecting negative cycles using Bellman-Ford algorithm

Revision en4, by oos1111, 2018-06-27 04:38:48

When we use Bellman-Ford to get single source shortest path, we usually initialize the distance of all vertices to be INF and then set dis[src] to be 0, and next we run the algorithm. But now I don't want to get any shortest path, instead I want to find a negative cycle in the graph if there exists any. Since I don't have any source vertex now, how should I initialize the distance of vertices at first?

I think we can do the same initialization when we try to find the single source shortest path, so we can pick any vertex v as the source, namely setting dis[v] to be 0 and setting distance of all other vertices to be INF, and then run the algorithm. But this seems to be wrong. And the correct initialization seems to be setting distance of all vertices to be 0.

This confused me a lot. So I have two question:
1. How should I initialize the distance of vertices when I want to find a negative cycle in a graph?
2. Is it wrong if I pick any vertex as source and run Bellman-Ford when I try to find a negative cycle? And Why if this is wroong?

And here is the case where the above two choices of initialization give us the difference:
problem: poj 2175

Description:

The City has a number of municipal buildings and a number of fallout shelters that were build specially to hide municipal workers in case of a nuclear war. Each fallout shelter has a limited capacity in terms of a number of people it can accommodate, and there's almost no excess capacity in The City's fallout shelters. Ideally, all workers from a given municipal building shall run to the nearest fallout shelter. However, this will lead to overcrowding of some fallout shelters, while others will be half-empty at the same time.

To address this problem, The City Council has developed a special evacuation plan. Instead of assigning every worker to a fallout shelter individually (which will be a huge amount of information to keep), they allocated fallout shelters to municipal buildings, listing the number of workers from every building that shall use a given fallout shelter, and left the task of individual assignments to the buildings' management. The plan takes into account a number of workers in every building — all of them are assigned to fallout shelters, and a limited capacity of each fallout shelter — every fallout shelter is assigned to no more workers then it can accommodate, though some fallout shelters may be not used completely.

The City Council claims that their evacuation plan is optimal, in the sense that it minimizes the total time to reach fallout shelters for all workers in The City, which is the sum for all workers of the time to go from the worker's municipal building to the fallout shelter assigned to this worker.

The City Mayor, well known for his constant confrontation with The City Council, does not buy their claim and hires you as an independent consultant to verify the evacuation plan. Your task is to either ensure that the evacuation plan is indeed optimal, or to prove otherwise by presenting another evacuation plan with the smaller total time to reach fallout shelters, thus clearly exposing The City Council's incompetence.

During initial requirements gathering phase of your project, you have found that The City is represented by a rectangular grid. The location of municipal buildings and fallout shelters is specified by two integer numbers and the time to go between municipal building at the location (Xi, Yi) and the fallout shelter at the location (Pj, Qj) is Di,j = |Xi — Pj| + |Yi — Qj| + 1 minutes.

Input

The input consists of The City description and the evacuation plan description. The first line of the input file consists of two numbers N and M separated by a space. N (1 ≤ N ≤ 100) is a number of municipal buildings in The City (all municipal buildings are numbered from 1 to N). M (1 ≤ M ≤ 100) is a number of fallout shelters in The City (all fallout shelters are numbered from 1 to M).

The following N lines describe municipal buildings. Each line contains there integer numbers Xi, Yi, and Bi separated by spaces, where Xi, Yi (-1000 ≤ Xi, Yi ≤ 1000) are the coordinates of the building, and Bi (1 ≤ Bi ≤ 1000) is the number of workers in this building.

The description of municipal buildings is followed by M lines that describe fallout shelters. Each line contains three integer numbers Pj, Qj, and Cj separated by spaces, where Pi, Qi (-1000 ≤ Pj, Qj ≤ 1000) are the coordinates of the fallout shelter, and Cj (1 ≤ Cj ≤ 1000) is the capacity of this shelter.

The description of The City Council's evacuation plan follows on the next N lines. Each line represents an evacuation plan for a single building (in the order they are given in The City description). The evacuation plan of ith municipal building consists of M integer numbers Ei,j separated by spaces. Ei,j (0 ≤ Ei,j ≤ 1000) is a number of workers that shall evacuate from the ith municipal building to the jth fallout shelter.

The plan in the input file is guaranteed to be valid. Namely, it calls for an evacuation of the exact number of workers that are actually working in any given municipal building according to The City description and does not exceed the capacity of any given fallout shelter.

Output

If The City Council's plan is optimal, then write to the output the single word OPTIMAL. Otherwise, write the word SUBOPTIMAL on the first line, followed by N lines that describe your plan in the same format as in the input file. Your plan need not be optimal itself, but must be valid and better than The City Council's one.

Sample Input

3 4
-3 3 5
-2 -2 6
2 2 5
-1 1 3
1 1 4
-2 -2 7
0 -1 3
3 1 1 0
0 0 6 0
0 3 0 2

Sample Output

SUBOPTIMAL
3 0 1 1
0 0 6 0
0 4 0 1

Accepted code:

#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>

using namespace std;

#define int_ int64_t
#define pb push_back
#define mp make_pair
#define ll long long
#define ull unsigned ll
#define db double
#define INF 0x3f3f3f3f
#define MOD 1000000007
#define PII pair<int, int>

const int N=105;
int n,m,x[N],y[N],b[N],p[N],q[N],c[N];
int d[2*N][2*N],e[N][N];
int dis[2*N],prevv[2*N];
bool vis[2*N];

int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++) scanf("%d%d%d",x+i,y+i,b+i);
    for (int i=1;i<=m;i++) scanf("%d%d%d",p+i,q+i,c+i);
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=m;j++) {
            scanf("%d",&e[i][j]);
        }
    }
    memset(d,INF,sizeof(d));
    int sink=m+n+1;
    for (int j=1;j<=m;j++) {
        int sum=0;
        for (int i=1;i<=n;i++) {
            int tmp=abs(x[i]-p[j])+abs(y[i]-q[j])+1;
            d[i][j+n]=tmp;
            if (e[i][j]>0) {
                d[j+n][i]=-tmp;
            }
            sum+=e[i][j];
        }
        if (sum>0) {
            d[sink][j+n]=0;
        }
        if (sum<c[j]) {
            d[j+n][sink]=0;
        }
    }
    int last=-1;
    memset(dis,0,sizeof(dis));
    bool update=true;
    int cnt=0;
    while (update) {
        update=false;
        for (int i=1;i<=sink;i++) {
            for (int j=1;j<=sink;j++) {
                if (dis[j]>dis[i]+d[i][j]) {
                    dis[j]=dis[i]+d[i][j];
                    prevv[j]=i;
                    update=true;
                    if (cnt+1==sink) last=j;
                }
            }
        }
        if (++cnt>=sink) break;
    }
    if (cnt<sink) {
        printf("OPTIMAL\n");
        return 0;
    }
    int cp=last;
    memset(vis,0,sizeof(vis));
    while (!vis[cp]) {
        vis[cp]=true;
        cp=prevv[cp];
    }
    memset(vis,0,sizeof(vis));
    for (int x=cp;!vis[x];x=prevv[x]) {
        vis[x]=true;
        if (x!=sink&&prevv[x]!=sink) {
            if (x>n) {
                e[prevv[x]][x-n]++;
            } else {
                e[x][prevv[x]-n]--;
            }
        }
    }
    printf("SUBOPTIMAL\n");
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=m;j++) {
            printf("%d%c",e[i][j],j==m?'\n':' ');
        }
    }
}

Wrong answer

#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>

using namespace std;

#define int_ int64_t
#define pb push_back
#define mp make_pair
#define ll long long
#define ull unsigned ll
#define db double
#define INF 0x3f3f3f3f
#define MOD 1000000007
#define PII pair<int, int>

const int N=105;
int n,m,x[N],y[N],b[N],p[N],q[N],c[N];
int d[2*N][2*N],e[N][N];
int dis[2*N],prevv[2*N];
bool vis[2*N];

int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++) scanf("%d%d%d",x+i,y+i,b+i);
    for (int i=1;i<=m;i++) scanf("%d%d%d",p+i,q+i,c+i);
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=m;j++) {
            scanf("%d",&e[i][j]);
        }
    }
    memset(d,INF,sizeof(d));
    int sink=m+n+1;
    for (int j=1;j<=m;j++) {
        int sum=0;
        for (int i=1;i<=n;i++) {
            int tmp=abs(x[i]-p[j])+abs(y[i]-q[j])+1;
            d[i][j+n]=tmp;
            if (e[i][j]>0) {
                d[j+n][i]=-tmp;
            }
            sum+=e[i][j];
        }
        if (sum>0) {
            d[sink][j+n]=0;
        }
        if (sum<c[j]) {
            d[j+n][sink]=0;
        }
    }
    bool update=true;
    int last=-1;
    int cnt=0;
    memset(dis,INF,sizeof(dis));
    dis[sink]=0;
    while (update) {
        update=false;
        for (int i=1;i<=sink;i++) {
            for (int j=1;j<=sink;j++) {
                if (dis[j]>dis[i]+d[i][j]) {
                    dis[j]=dis[i]+d[i][j];
                    last=j;
                    prevv[j]=i;
                    update=true;
                }
            }
        }
        if (++cnt>=sink) break;
    }
    if (cnt<sink) {
        printf("OPTIMAL\n");
        return 0;
    }
    int cp=last;
    memset(vis,0,sizeof(vis));
    while (!vis[cp]) {
        vis[cp]=true;
        cp=prevv[cp];
    }
    memset(vis,0,sizeof(vis));
    for (int x=cp;!vis[x];x=prevv[x]) {
        vis[x]=true;
        if (x!=sink&&prevv[x]!=sink) {
            if (x>n) {
                e[prevv[x]][x-n]++;
            } else {
                e[x][prevv[x]-n]--;
            }
        }
    }
    printf("SUBOPTIMAL\n");
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=m;j++) {
            printf("%d%c",e[i][j],j==m?'\n':' ');
        }
    }
}

We cannot solve this problem by finding minimum cost flow because it will get TLE and we don't need find the optimal. Instead we find a negative cycle and optimize the answer. The only difference of the above two code is the initialization of dis. Why is second one wrong? Please help.

Tags graph, shortest-path, bellman-ford, negative cycle

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English oos1111 2018-06-27 04:38:48 0 Tiny change: 'zation of disdisdis. Why is s' -> 'zation of `dis`. Why is s' (published)
en3 English oos1111 2018-06-27 04:37:39 9842
en2 English oos1111 2018-06-27 04:13:24 539
en1 English oos1111 2018-06-27 04:04:57 755 Initial revision (saved to drafts)