# bzoj 1977 洛谷P4180 严格次小生成树

Description：

给定一张N个节点M条边的无向图，求该图的严格次小生成树。设最小生成树边权之和为sum，那么严格次小生成树就是边权之和大于sum的最小的一个

Input：

Output：

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
#define ll long long

struct edges{
int u, to, next, w;
}edge[N<<1];

struct input{
int u, v, w;
}E[N];
int n, m, father[N], fa[N][25];
ll mx[N][25], d[N], tot;
bool vis[N];

int get(int x){
if(x != father[x]) return father[x] = get(father[x]);
return x;
}
bool cmp(input x, input y){ return x.w < y.w; }
void kruskal(){
sort(E + 1, E + m + 1, cmp);
for(int i = 1; i <= n; i++) father[i] = i;
for(int i = 1; i <= m; i++){
int x = get(E[i].u), y = get(E[i].v);
if(x != y) father[y] = x, tot += E[i].w, add(E[i].u, E[i].v, E[i].w), add(E[i].v, E[i].u, E[i].w), vis[i] = 1;
}
}
void dfs(int x,int pre, int deep){
fa[x][0] = pre; d[x] = deep;
for(int i = head[x]; i; i = edge[i].next){
int v = edge[i].to;
if(v == pre) continue;
mx[v][0] = edge[i].w;
dfs(v, x, deep + 1);
}
}
void work(){
for(int j = 1; j <= 20; j++)
for(int i = 1; i <= n; i++){
fa[i][j] = fa[fa[i][j - 1]][j - 1];
mx[i][j] = max(mx[i][j - 1], mx[fa[i][j - 1]][j - 1]);
}

}
ll getmax(int x,int y, int z){
if(y == -1) return 0;
if(mx[x][y] == z) return max(getmax(x, y - 1, z), getmax(fa[x][y - 1], y - 1, z));
return mx[x][y];
}
ll query(int x, int y, int z){
ll maxn = 0;
if(d[x] < d[y]) swap(x, y);
if(d[x] ^ d[y])
for(int i = 20; i >= 0; i--)
if(d[fa[x][i]] >= d[y]) maxn = max(maxn, getmax(x, i, z)), x = fa[x][i];
if(x == y) return z - maxn;
for(int i = 20; i >= 0; i--){
if(fa[x][i] != fa[y][i]){
maxn = max(maxn, max(getmax(x, i, z), getmax(y, i, z)));
x = fa[x][i], y = fa[y][i];
}
}
return z - max(maxn, max(getmax(x, 0, z), getmax(y, 0, z)));
}
int main(){
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++)
scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].w);
kruskal();
dfs(1, 1, 1);
work();
ll ans = 1e18;
for(int i = 1; i <= m; i++)
if(!vis[i]){
ll tmp = query(E[i].u, E[i].v, E[i].w);
if(tmp) ans = min(ans, tot + tmp);
}
printf("%lld\n", ans);
return 0;
} 
View Code

posted @ 2018-04-01 00:00  Ror_shach  阅读(394)  评论(0编辑  收藏  举报