Give an image with no direction, each vertex has the right value to remove an edge and divide the graph into two parts
Ask the minimum value of all the vertices and the absolute values of the two parts
Use a Tarjan to indent a point and then a tree
Then the minimum absolute value of the tree-shaped DP is obtained.
ans = min (ans, (int) (ABS ((double) (SUM-2*DP[V))));
Where Dp[u] represents the number of students in a subtree with a U point as the root node
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <vector>
using namespace Std;
const int MAXN = 10010;
const int MAXM = 20010;
const int inf = 0X7FFFFFFF;
struct Edge
{
int V, u;
int next;
}edge[maxm<<1];
int HEAD[MAXN], DFN[MAXN], LOW[MAXN], vis[maxm<<1];
int STACK[MAXN], ISSTACK[MAXN], VALUE[MAXN], DP[MAXN];
int Nedge, top, num, step, sum;
int n, m; int BELONG[MAXN], STU[MAXN];
void Addedge (int u, int v)
{
EDGE[NEDGE].V = v;
Edge[nedge].next = Head[u];
Head[u] = nedge++;
}
Vector<int> VEC[MAXN];
void Init ()
{
memset (Vis, 0, sizeof (VIS));
memset (DFN, 0, sizeof (DFN));
memset (Low, 0, sizeof (low));
memset (isstack, 0, sizeof (isstack));
memset (value, 0, sizeof (value));
memset (head, -1, sizeof (head));
memset (DP, 0, sizeof (DP));
for (int i = 0; I <= n;i++)
Vec[i].clear ();
top = num = Step = Nedge = SUM = 0;
}
void Tarjan (int u)
{
Isstack[u] = 1;
Stack[++top] = u;
Dfn[u] = low[u] = ++step;
for (int i = head[u];i! =-1; i = edge[i].next)
{
if (Vis[i]) continue;
Vis[i] = vis[i^1] = 1;
int v = EDGE[I].V;
if (!dfn[v])
{
Tarjan (v);
Low[u] = min (Low[u], low[v]);
}
else if (Isstack[v])
Low[u] = min (Low[u], dfn[v]);
}
if (dfn[u] = = Low[u])
{
num++;
int V;
while (U!=V)
{
v = stack[top--];
BELONG[V] = num;
ISSTACK[V] = 0;
Value[num] + = Stu[v];
}
}
}
void Build_tree ()
{
for (int i = 1;i <= n;i++)
for (int j = head[i]; J! =-1; j = edge[j].next)
{
int u = belong[i];
int v = belong[edge[j].v];
if (U = = v) continue;
Vec[u].push_back (v);
}
}
void Dfs (const int u, int &ans)
{
Vis[u] = 1;
for (int i = 0;i < Vec[u].size (); i++)
{
int v = vec[u][i];
if (Vis[v]) continue;
DFS (v, ans);
ans = min (ans, (int) (ABS ((double) (SUM-2*DP[V))));
Dp[u] + = Dp[v];
}
Dp[u] + = Value[u];
}
int main ()
{
Freopen ("In.txt", "R", stdin);
while (~SCANF ("%d%d", &n, &m))
{
int A, B;
Init ();
for (int i = 1;i <= n;i++)
{
scanf ("%d", &stu[i]);
Sum + = Stu[i];
}
for (int i = 1;i <= m;i++)
{
scanf ("%d%d", &a, &b);
Addedge (a+1, b+1);
Addedge (b+1, a+1);
}
int ans = inf;
Tarjan (1);
Build_tree ();
if (num <= 1) puts ("impossible");
Else
{
memset (Vis, 0, sizeof (VIS));
DFS (1, ans);
printf ("%d\n", ans);
}
}
return 0;
}
hdu2422 the boundless--air-conditioning classroom tarjan+ tree DP