时间复杂度O(V ^ 3)或O(V ^ 2)?

时间:2015-03-11 13:55:08

标签: algorithm time-complexity

我是分析算法和时间的新手。这个算法发布在http://geeksforgeeks.com中,他们写道算法的时间复杂度是O(V ^ 2)我认为它是O(V ^ 3):

    int minDistance(int dist[], bool sptSet[])
{
   // Initialize min value
   int min = INT_MAX, min_index;

   for (int v = 0; v < V; v++)
     if (sptSet[v] == false && dist[v] <= min)
         min = dist[v], min_index = v;

   return min_index;
}

// A utility function to print the constructed distance array
int printSolution(int dist[], int n)
{
   printf("Vertex   Distance from Source\n");
   for (int i = 0; i < V; i++)
      printf("%d \t\t %d\n", i, dist[i]);
}

// Funtion that implements Dijkstra's single source shortest path algorithm
// for a graph represented using adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
     int dist[V];     // The output array.  dist[i] will hold the shortest
                      // distance from src to i

     bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest
                     // path tree or shortest distance from src to i is finalized

     // Initialize all distances as INFINITE and stpSet[] as false
     for (int i = 0; i < V; i++)
        dist[i] = INT_MAX, sptSet[i] = false;

     // Distance of source vertex from itself is always 0
     dist[src] = 0;

     // Find shortest path for all vertices
     for (int count = 0; count < V-1; count++)
     {
       // Pick the minimum distance vertex from the set of vertices not
       // yet processed. u is always equal to src in first iteration.
       int u = minDistance(dist, sptSet);

       // Mark the picked vertex as processed
       sptSet[u] = true;

       // Update dist value of the adjacent vertices of the picked vertex.
       for (int v = 0; v < V; v++)

         // Update dist[v] only if is not in sptSet, there is an edge from 
         // u to v, and total weight of path from src to  v through u is 
         // smaller than current value of dist[v]
         if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX 
                                       && dist[u]+graph[u][v] < dist[v])
            dist[v] = dist[u] + graph[u][v];
     }

     // print the constructed distance array
     printSolution(dist, V);
}

图形表示在图形[] [](矩阵表示)中。

提前致谢

1 个答案:

答案 0 :(得分:2)

解决方案确实是O(V ^ 2):

 for (int i = 0; i < V; i++)
    dist[i] = INT_MAX, sptSet[i] = false;

这部分在主循环之前运行,并且在O(V)的复杂性中运行。

 for (int count = 0; count < V-1; count++)
 {

这是主循环,整体运行O(V)次,每次需要:

   int u = minDistance(dist, sptSet);

每个count的不同值运行一次,其复杂度为O(V),所以我们现在有O(V ^ 2)`。

  sptSet[u] = true;

这是O(1),运行O(V)次。

   for (int v = 0; v < V; v++)

此循环运行O(V)次,对于count的每个值,让我们检查每次运行时会发生什么:

    if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX 
                                   && dist[u]+graph[u][v] < dist[v])
        dist[v] = dist[u] + graph[u][v];

所有这些都是O(1),每个(count,v)对完成,并且有O(V^2)对。

所以,完全O(V^2)


请注意,为了更有效的图形表示,我们可以在O(E + VlogV)中运行Dijkstra算法,这在稀疏图形的情况下可能更好。