仙人掌DP
每次在环上DP的时候强制一下环上的根(即环上第一个被发现的节点)左边的节点取或不取
#include<iostream> #include<cstdio> #include<cstring> #include<vector> using namespace std; const int N=100000+5; const int inf=1e9; struct Edge{int to,next;}e[N<<2]; int head[N],cnt; void ins(int u,int v){ e[++cnt]=(Edge){v,head[u]};head[u]=cnt; } int power[N],f[N],g[N],pre[N]; void dp(int rt,int x){ int ans0=0,ans1=0,now0,now1; for(int i=x;i!=rt;i=pre[i]){ now0=ans0+g[i];now1=ans1+f[i]; ans0=max(now0,now1);ans1=now0; } g[rt]+=ans0; ans0=0;ans1=-inf; for(int i=x;i!=rt;i=pre[i]){ now0=ans0+g[i];now1=ans1+f[i]; ans0=max(now0,now1);ans1=now0; } f[rt]+=ans1; } int dfn[N],dfs_clock; void dfs(int u){ dfn[u]=++dfs_clock; for(int i=head[u];i;i=e[i].next){ int v=e[i].to; if(!dfn[v])pre[v]=u,dfs(v); } f[u]=power[u]; for(int i=head[u];i;i=e[i].next){ int v=e[i].to; if(dfn[v]>dfn[u]&&pre[v]!=u) dp(u,v); } } int main(){ //freopen("a.in","r",stdin); int n,m;scanf("%d%d",&n,&m); while(m--){ int u,v;scanf("%d%d",&u,&v); ins(u,v);ins(v,u); } for(int i=1;i<=n;i++)scanf("%d",&power[i]); dfs(1); printf("%d\n",max(f[1],g[1])); return 0; }