題目鏈接:洛谷 P3577
題目大意:n個點,m條邊的無向圖(2<=n<=20000,0<=m<=25000),圖中任意兩點間不存在節點數超過10的簡單路徑。給出在每個點建立旅遊站點的花費,問最小花費,使得每個點要麼建立了旅遊站點,要麼與它有邊直接相連的點裏至少有一個點建立了旅遊站點。
題解:任意兩點間不存在節點數超過10的簡單路徑,說明對圖進行dfs得到的dfs樹的深度不超過10,這樣就可以對每個聯通塊分別三進制狀壓DP,f[dep][sta]表示深度爲dep的點,連同祖先的狀態爲sta時的最小花費,狀態中的0表示建了旅遊站點,2表示沒有建旅遊站點但相鄰節點中有至少一個點建了旅遊站點,1表示沒有建旅遊站點且相鄰節點也沒有建旅遊站點。
轉移的時候先從祖先轉移,再從子樹轉移,有點類似於揹包泛化物品的合併。比較巧妙,具體見代碼。
code(感覺轉移很妙呀(*╹▽╹*))
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 25005
#define inf 1000000000
using namespace std;
inline int read()
{
char c=getchar(); int num=0,f=1;
while (c<'0'||c>'9') { if (c=='-') f=-1; c=getchar(); }
while (c<='9'&&c>='0') { num=num*10+c-'0'; c=getchar(); }
return num*f;
}
struct edge{
int to,ne;
}e[N<<1];
int n,m,tot,head[N],c[N],tur[15],f[15][60005],deep[N],tmp[N],ans;
bool vis[N];
inline void push(int x,int y)
{
e[++tot].to=y; e[tot].ne=head[x]; head[x]=tot;
e[++tot].to=x; e[tot].ne=head[y]; head[y]=tot;
}
inline int wei(int sta,int w) { return (sta/tur[w])%3; }
void dfs(int now)
{
vis[now]=true; int dep=deep[now];
if (!dep) f[dep][0]=c[now],f[dep][1]=0,f[dep][2]=inf;
else //從祖先轉移
{
int cnt=0;
for (int i=head[now];i;i=e[i].ne)
{
int v=e[i].to;
if (vis[v]&&deep[v]<dep) tmp[++cnt]=deep[v];
}
for (int sta=0;sta<tur[dep+1];sta++) f[dep][sta]=inf;
for (int sta=0;sta<tur[dep];sta++)
{
int t=1,s0=sta;
for (int i=1;i<=cnt;i++)
{
int w=wei(sta,tmp[i]);
if (w==0) t=2;
else if (w==1) s0+=tur[tmp[i]];
}
f[dep][sta+t*tur[dep]]=min(f[dep][sta+t*tur[dep]],f[dep-1][sta]);
f[dep][s0]=min(f[dep][s0],f[dep-1][sta]+c[now]);
}
}
for (int i=head[now];i;i=e[i].ne) //子樹的合併,類似於揹包
{
int v=e[i].to; if (vis[v]) continue;
deep[v]=deep[now]+1; dfs(v);
for (int sta=0;sta<tur[dep+1];sta++)
f[dep][sta]=min(f[dep+1][sta],f[dep+1][sta+2*tur[dep+1]]);
//這裏的min類似於揹包泛化物品,比較神奇
}
}
int main()
{
tur[0]=1; for (int i=1;i<=13;i++) tur[i]=tur[i-1]*3;
n=read(); m=read();
for (int i=1;i<=n;i++) c[i]=read();
for (int i=1;i<=m;i++) push(read(),read());
for (int i=1;i<=n;i++)
if (!vis[i]) dfs(i),ans+=min(f[0][0],f[0][2]);
// f[dep][sta]表示深度爲dep的點,連同祖先的狀態爲sta時的最小花費
printf("%d",ans);
return 0;
}