E - Minimum spanning tree for each edge

这个题目参考网上的思路。

首先求个最小生成树,然后每加一条边,就把成环的里面除加入的这条边的最大的删除,就是答案。

最小生成树用 克鲁斯卡尔 弄一弄,边弄最小生成树的时候边建树。
然后用lca搞一搞就行了。
部分代码如下

void dfs(int u,int fz,int dp){
    deep[u] = dp;
    fa[u][0]=fz;
    for(int i=head[u];~i;i=E[i].forword){
        int now = E[i].to;
        if(now==fz){
            mx[u][0]=E[i].cost; 
            continue;
        }
        dfs(now,u,dp+1);
    }
};
int lca(int u,int v){
    int ret=0;
    while(deep[u]!=deep[v]){
        if(deep[u]<deep[v]) swap(u,v);
        int d = deep[u] - deep[v];
        for(int i=0;i<25;i++){
            if(d>>i&1){
                ret = max(ret,mx[u][i]);
                u = fa[u][i];
            }
        }
    }
    if(u==v) return ret;
    for(int i=24;i>=0;i--){
        if(fa[u][i] != fa[v][i]) {  
            ret = max(ret, mx[u][i]);  
            ret = max(ret, mx[v][i]);  
            u = fa[u][i];  
            v = fa[v][i];  
        }
    }
    return max(ret,max(mx[u][0],mx[v][0]));
}
以下是使用Matlab实现最小生成树(MST)算法的示例代码: ``` function [T, W] = mst_prim(A) % MST_PRIM Minimum Spanning Tree using Prim's algorithm % [T, W] = MST_PRIM(A) computes the minimum spanning tree T and its weight % W of the graph A using Prim's algorithm. % % Input: % A - n-by-n adjacency matrix of the graph. % % Output: % T - n-by-n sparse matrix of the minimum spanning tree. T(i,j) = 1 if % there is an edge between i and j in the minimum spanning tree, % and 0 otherwise. % W - the weight of the minimum spanning tree. % % Author: Zhiqiang Wang, zwang@ieee.org % Date: 07/01/2018 n = size(A, 1); % number of vertices T = sparse(n, n); % initialize the minimum spanning tree W = 0; % initialize the weight of the minimum spanning tree key = inf(1, n); % the minimum key value of each vertex pi = zeros(1, n); % the parent vertex of each vertex visited = false(1, n); % the visited flag of each vertex key(1) = 0; % start from vertex 1 for i = 1:n % find the unvisited vertex with the minimum key value u = find(~visited & (key == min(key)), 1); visited(u) = true; if pi(u) ~= 0 T(u, pi(u)) = 1; % add the edge to the minimum spanning tree T(pi(u), u) = 1; W = W + A(u, pi(u)); % update the weight of the minimum spanning tree end % update the key values of the adjacent vertices for v = 1:n if A(u, v) ~= 0 && ~visited(v) && A(u, v) < key(v) key(v) = A(u, v); pi(v) = u; end end end ``` 该代码使用Prim算法,输入为一个n-by-n的邻接矩阵A,输出为一个n-by-n的稀疏矩阵T和最小生成树的权重W。其中,稀疏矩阵T中T(i,j)=1表示最小生成树中存在一条从i到j的边,否则T(i,j)=0。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值