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.
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.