關於次小生成樹 Tree
小 C 最近學了很多最小生成樹的算法
Input
第一行包含兩個整數N 和M
Output
包含一行
Sample Input
Sample Output
HINT
數據中無向圖無自環;
Source
這題的關鍵就在於求Lca
用f[i][j]表示i的第
那麼f[i][j]=f[ f[i][ j
dp[i][j]和dp
[cpp]
int lca(int x
{
if (deep[x]<deep[y]) swap(x
int t=deep[x]
for (int i=
if (t&bin[i]) //轉化為位運算 bin[i]表示
{
x=f[x][i];
t
}
int i=Li
while (x^y) //x和y不相等時
{
while (f[x][i]==f[y][i]&&i) i
x=f[x][i];y=f[y][i];
}
}
程序
[cpp]
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define MAXN (
#define MAXM (
#define Li (
#define INF (
int edge[MAXM]
int addedge(int u
{
edge[++size]=v;
weight[size]=w;
next[size]=pre[u];
pre[u]=size;
}
int addedge
{
addedge(u
addedge(v
}
int f[MAXN][Li]={
struct E
{
int u
friend bool operator<(E a
}e[MAXM];
bool b[MAXM]
int queue[MAXN]
void bfs()
{
memset(vis
head=tail=
while (head<=tail)
{
int &u=queue[head];
if (u!=
{
for (int i=
{
if (f[u][i
{
f[u][i]=f[f[u][i
}
if (f[u][i]==
if (f[u][i])
{
dp[u][i]=max(dp[u][i
}
if (i==
{
if (dp[u][
else dp
}
else
{
dp
if (dp[u][i
}
}
}
for (int p=pre[u];p;p=next[p])
{
int &v=edge[p];
if (!vis[v])
{
queue[++tail]=v;
vis[v]=
f[v][
}
}
head++;
}
}
int bin[Li];
void check(int &nowdp
{
if (c<=nowdp
else if (nowdp
else if (c==nowdp) return;
else if (nowdp<c) {nowdp
}
int lca(int x
{
nowdp=nowdp
if (deep[x]<deep[y]) swap(x
int t=deep[x]
for (int i=
if (t&bin[i])
{
check(nowdp
check(nowdp
x=f[x][i];
t
}
int i=Li
while (x^y)
{
while (f[x][i]==f[y][i]&&i) i
check(nowdp
check(nowdp
check(nowdp
check(nowdp
x=f[x][i];y=f[y][i];
}
}
int father[MAXN];
long long sum_edge=
int getfather(int x)
{
if (father[x]==x) return x;
father[x]=getfather(father[x]);
return father[x];
}
void union
{
father[father[x]]=father[father[y]];
}
int main()
{
scanf(
for (int i=
memset(b
memset(next
for (int i=
for (int i=
{
scanf(
}
sort(e+
for (int i=
{
if (getfather(e[i]
else b[i]=
}
bfs();
long long mindec=
for (int i=
if (b[i])
{
int nowdp
lca(e[i]
if (nowdp==e[i]
if (nowdp==
if (mindec==
}
printf(
return
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26453.html