简体   繁体   中英

How can I find a negative weighted cycle of 3 edges in a graph?

I have a directed graph with about 10,000 nodes. All edges are weighted. I want to find a negative cycle containing only 3 edges. Is there any algorithm quicker than O(n^3)?

a sample code: (g is my graph)

if (DETAILS) std::printf  ("Calculating cycle of length 3.\n");
for (int i=0;i<NObjects;i++)
{
    for (int j=i+1;j<NObjects;j++)
    {
        for (int k=j+1;k<NObjects;k++)
        {
            if ((d= g[i][j]+g[j][k]+g[k][i])<0)
            {
                results[count][0] = i;
                results[count][1] = j;
                results[count][2] = k;
                results[count][3] = d;
                count++;
                if (count>=MAX_OUTPUT_SIZE3)
                    goto finish3;
            }

            if ((d= g[i][k]+g[k][j]+g[j][i])<0)
            {
                results[count][0] = j;
                results[count][1] = i;
                results[count][2] = k;
                results[count][3] = d;
                count++;
                if (count>=MAX_OUTPUT_SIZE3)
                    goto finish3;
            }
        }

    }
}
finish3:

I cannot think of any algorithm with definite comlexity lower than O(n 3 ), but also the constant factor is important in practice. The following algorithm allows pruning to speed up finding a cycle of length 3 with negative sum of weights - or checking that there is no such cycle.

  1. sort the (directed) edges according to their weight
  2. take the edge with the lowest weight as starting edge.
  3. try all edges connected to the end vertex of the starting edge with a weight not lower than the starting edge (1st pruning) and check the sum of weights when you close the cycle. If you find a cycle with negative sum you are done.
  4. continue with the edge with the next lowest weight as the starting edge. If its weight is negative goto 3 - otherwise you are done (2nd pruning)

The idea is that at least one of the edges of a cylce with negative sum must have a negative weight. And that we can start a cycle at the edge with lowest weight in the cycle.

If you know that the number edges with negative weights is O(n) then this algorithm will be O(n 2 ld n) since the algorithm will then be dominated by step 1 (= sorting the edges according to their weight).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM