分析Prim算法实现的复杂性

时间:2015-07-12 15:58:57

标签: c++ graph time-complexity

这是Prim的实施!事实上,这是非常复杂和缓慢的,更好的版本是here但我仍然想知道下面代码的时间复杂性。您也可以在此处检查相同的代码nice colors and indentation

#include <bits/stdc++.h>
using namespace std;

const int size = 12345;
int unionArray[size];
int degree[size];

struct comp {
    bool operator()(const pair<int, pair<int, int> > & ppa, const pair<int, pair<int, int> > &ppb) {
        return ppa.first > ppb.first;
    }
};

int root(int a) {
    while(unionArray[a] != a) {
        unionArray[a] = unionArray[unionArray[a]];
        a = unionArray[a];
    }
    return a;
}

bool unionFunction(int a, int b) {
    int root_a = root(a);
    int root_b = root(b);
    if(root_a == root_b)
        return false;
    if(root_a < root_b) {
        unionArray[root_a] = root_b;
        degree[root_b] += degree[root_a];
    }
    else {
        unionArray[root_b] = root_a;
        degree[root_a] += root_b;
    }
    return true;
}

int main(void) {

    int N = 0, M = 0;
    scanf("%d %d", &N, &M);

    vector<pair<int, int> > adj[N + 1];

    for(int i = 0; i < N; ++i) {
        unionArray[i] = i;
        degree[i] = 1;
    }

    for(int i = 0; i < M; ++i) {
        int x = 0, y = 0, w = 0;
        scanf("%d %d %d", &x, &y, &w);
        adj[x].push_back(make_pair(y, w));
        adj[y].push_back(make_pair(x, w));
    }

    priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, comp > Q;


    for(auto it = adj[0].begin(); it != adj[0].end(); ++it)
        Q.push(make_pair(it->second, make_pair(0, it->first)));

    int res = 0;

    while(!Q.empty()) {
        int w = Q.top().first;
        pair<int, int> temp = Q.top().second;
        Q.pop();
        if(unionFunction(temp.first, temp.second)) {
            res += w;
            for(auto it = adj[temp.second].begin(); it != adj[temp.second].end(); ++it)
                Q.push(make_pair(it->second, make_pair(temp.first, it->first)));
        }
    }

    cout << res << "\n";
    return 0;
}
顺便说一句,如果我必须猜测它的复杂性,那么我的猜测将是O((E + V)(log*N)(log E))

0 个答案:

没有答案