码迷,mamicode.com
首页 > 其他好文 > 详细

次小生成树 - 堆优化

时间:2017-11-10 18:26:17      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:i++   int   min   amp   fun   priority   continue   ns2   bool   

const int inf = 1<<29;
int n, m;
int edge[105][105];
bool vis[105];
int d[105];
int mm[105][105];
int pre[105];
bool used[105][105];

struct node
{
    int v, c;
    node(int _v = 0, int _c = 0):v(_v), c(_c){}
    friend bool operator< (node n1, node n2){
        return n1.c > n2.c;
    }
};
int ans, ans2;

void prim(){
    priority_queue<node>que;
    while(!que.empty()) que.pop();
    memset(mm, 0, sizeof(mm));
    memset(pre, 0, sizeof(pre));
    memset(used, false, sizeof(used));    
    memset(vis, false, sizeof(vis));
    for(int i = 1; i <= n; i++){
        d[i] = edge[1][i];
        pre[i] = 1;
        if (d[i] < inf) { 
            que.push(node(i, d[i])); 
        }
    }
    
    vis[1] = true;
    ans = 0;
    int cnt = 0;
    while(!que.empty()){
        node tem = que.top();
        que.pop();
        int v = tem.v;
        int c = tem.c;
        
        if (vis[v]) continue;
        vis[v] = true;
      
        ans += c;
        cnt++; 
        used[v][pre[v]] = used[pre[v]][v] = true;
        for(int i = 1; i <= n; i++){
            if (vis[i]) mm[i][v] = mm[v][i] = max(d[v], mm[i][pre[v]]);
      
            if (!vis[i] && edge[v][i] < d[i]){
                d[i] = edge[v][i];
                pre[i] = v;
                que.push(node(i, d[i]));
            }
        }
        if (cnt == n - 1) break;
    }
    if (cnt < n-1) ans = -1;
}

void fun(){
    ans2 = inf;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
           
            if (!used[i][j] && edge[i][j] < inf){
                ans2 = min(ans2, ans+edge[i][j]-mm[i][j]);    
            }
        }
    }
}

 

次小生成树 - 堆优化

标签:i++   int   min   amp   fun   priority   continue   ns2   bool   

原文地址:http://www.cnblogs.com/ccut-ry/p/7815620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!