最小生成树时间复杂度

时间:2013-06-28 18:03:15

标签: algorithm graph time-complexity

我有Prim Algo的MST实现,即| V |对权力3。但CLRS表示,假设| V |,复杂度为O(E * lg | V |) 〜| E |它的O(| V | * lg | V |)。我的实施可能是固定的,但我不确定我们怎么能低于| V | * | V |使用矩阵实现

class matrix_graph
{
private:
    int** v;
    int vertexes;
public:
    matrix_graph(int**, int);
    ~matrix_graph(void);
    bool is_connected(int i,int j);
    int egde_weight(int i,int j){return v[i][j];}
};






int mst()
{
    int v[9][9] = {  
        {0,4,0,0,0,0,0,0,8},
        {0,0,8,0,0,0,0,0,11},
        {0,8,0,7,0,4,0,2,0},
        {0,0,7,0,9,14,0,0,0},
        {0,0,0,9,0,10,0,0,0},
        {0,0,4,14,10,0,2,0,0},
        {0,0,0,0,0,2,0,6,1},
        {0,0,2,0,0,0,6,0,7},
        {8,11,0,0,0,0,1,7,0}
    };

    int* ptr_v[9];
    for(int i=0;i<9;i++){
        ptr_v[i] = & v[i][0];
    }
    matrix_graph* m = new matrix_graph(ptr_v , 9 );

    std::set<int> tree;
    tree.insert(0);

        std::set<int> non_tree;
        non_tree.insert(1);
    non_tree.insert(2);
    non_tree.insert(3);
    non_tree.insert(4);
    non_tree.insert(5);
    non_tree.insert(6);
    non_tree.insert(7);
    non_tree.insert(8);

    int i = 0;
    int min = _I32_MAX;
    int add_to_tree;
    int sum = 0;

    while(!non_tree.empty()){
        for(std::set<int>::iterator iter = tree.begin() ; iter != tree.end() ; iter++ ){
            for(std::set<int>::iterator iter_n = non_tree.begin() ; iter_n != non_tree.end() ; iter_n++){
                int edge = m->egde_weight(*iter , *iter_n);
                if( edge > 0 && edge < min)
                {
                    min = edge;
                    add_to_tree = *iter_n;
                }
            }
        }
        tree.insert(add_to_tree);
        non_tree.erase(add_to_tree);
        sum += min;
        min = _I32_MAX;
    }
    return sum;
}

1 个答案:

答案 0 :(得分:4)

您需要使用Adjacency list(而不是Adjacency Matrix)来表示图形。然后你的实现可以给出O(E * lg | V |)。

如果您还想进一步优化运行时间,可以使用Fibonacci堆来提取最小值。然后你可以实现O(| E | + V * lg | V |)运行时间。使用Fibonacci堆,您可以在运行的摊销O(lg n)中查找和删除元素。

更多详情:

http://en.wikipedia.org/wiki/Fibonacci_heap

斐波那契堆也在CLRS Book中讨论过。