题目地址:HDU 2242
先用双连通分量缩点,然后形成一棵树,然后在树上做树形DP,求出每个点的子树和。然后找最小值即可。需要注意一下重边的问题,第一次返回父节点时可以忽略,因为这是反向边,然后之后再返回的时候就不是反向边了。不能忽略了。
代码如下:
#include <iostream> #include <string.h> #include <math.h> #include <queue> #include <algorithm> #include <stdlib.h> #include <map> #include <set> #include <stdio.h> using namespace std; #define LL long long #define pi acos(-1.0) const int mod=1e9+7; const int INF=0x3f3f3f3f; const double eqs=1e-9; const int MAXN=10000+10; int head[MAXN], Ecnt, top, indx, scc; int low[MAXN], dfn[MAXN], belong[MAXN], stk[MAXN], dp[MAXN], a[MAXN]; struct node { int u, v, next; }edge[MAXN<<2]; void add(int u, int v) { edge[Ecnt].u=u; edge[Ecnt].v=v; edge[Ecnt].next=head[u]; head[u]=Ecnt++; } void tarjan(int u, int fa) { low[u]=dfn[u]=++indx; stk[++top]=u; int flag=1; for(int i=head[u];i!=-1;i=edge[i].next){ int v=edge[i].v; if(v==fa&&flag) { flag=0; continue ; } if(!dfn[v]){ tarjan(v,u); low[u]=min(low[u],low[v]); } else low[u]=min(low[u],dfn[v]); } if(low[u]==dfn[u]){ scc++; while(1){ int v=stk[top--]; belong[v]=scc; dp[scc]+=a[v]; if(u==v) break; } } } void init() { memset(head,-1,sizeof(head)); memset(dfn,0,sizeof(dfn)); memset(dp,0,sizeof(dp)); Ecnt=top=indx=scc=0; } int head1[MAXN], Ecnt1, vis[MAXN]; struct node1 { int u, v, next; }edge1[MAXN<<2]; void add1(int u, int v) { edge1[Ecnt1].v=v; edge1[Ecnt1].next=head1[u]; head1[u]=Ecnt1++; } void dfs(int u) { vis[u]=1; for(int i=head1[u];i!=-1;i=edge1[i].next){ int v=edge1[i].v; if(vis[v]) continue ; dfs(v); dp[u]+=dp[v]; } } void init1() { memset(head1,-1,sizeof(head1)); memset(vis,0,sizeof(vis)); Ecnt1=0; } int main() { int n, m, u, v, i, j, sum, min1; while(scanf("%d%d",&n,&m)!=EOF){ sum=0; for(i=0;i<n;i++){ scanf("%d",&a[i]); sum+=a[i]; } init(); while(m--){ scanf("%d%d",&u,&v); add(u,v); add(v,u); } for(i=0;i<n;i++){ if(!dfn[i]) tarjan(i,-1); } if(scc==1){ puts("impossible"); continue ; } init1(); for(i=0;i<n;i++){ for(j=head[i];j!=-1;j=edge[j].next){ v=edge[j].v; if(belong[i]!=belong[v]){ add1(belong[i],belong[v]); add1(belong[v],belong[i]); } } } dfs(1); min1=INF; for(i=1;i<=scc;i++){ min1=min(min1,abs(sum-2*dp[i])); } printf("%d\n",min1); } return 0; }