1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| #include<algorithm> #include<iostream> #include<cstring> #include<vector> #include<cmath> #include<set> const int Maxn = 10000 + 23; using namespace std;
class CutEdge { private: int N; int clk, pre[Maxn];
int DFS(int u, int f) { int lowu = pre[u] = ++clk; for (auto e = G[u].begin(); e != G[u].end(); ++e) { int v = *e; if (!pre[v]) { int lowv = DFS(v, u); lowu = min(lowu, lowv); if (lowv > pre[u]) { Cut[u].insert(v); Cut[v].insert(u); } } else if (pre[u] > pre[v]) { int cnt = 0; for (const auto &e : G[u]) if (e == v) ++cnt; if (cnt > 1 || v != f) { lowu = min(lowu, pre[v]); } } } return lowu; }
void DFS2(int u, int id) { ID[u] = id; for (const auto &v : G[u]) if (!ID[v]) { if (Cut[u].count(v)) { ++Num; G2[id].push_back(Num); G2[Num].push_back(id); DFS2(v, Num); } else DFS2(v, id); } }
public: vector<int> G[Maxn]; set<int> Cut[Maxn];
vector<int> G2[Maxn]; int ID[Maxn]; int Num;
void Clear(int n) { N = n; memset(ID, 0, sizeof(ID)); memset(pre, 0, sizeof(pre)); for (int i = 1; i <= N; ++i) { G[i].clear(); G2[i].clear(); Cut[i].clear(); } clk = 0; Num = 1; }
void AddEdge(int u, int v) { G[u].push_back(v); G[v].push_back(u); }
void Find() { for (int i = 1; i <= N; ++i) if (!pre[i]) DFS(i, -1); }
int BCC() { DFS2(1, Num); return Num; } };
int N, M; int V[Maxn]; int V2[Maxn]; int DP[Maxn]; bool vis[Maxn]; CutEdge C;
int DFS(int u) { vis[u] = true; DP[u] = V2[u]; for (const auto &v : C.G2[u]) { if (!vis[v]) DP[u] += DFS(v); } return DP[u]; }
int main() { ios::sync_with_stdio(false); while (cin >> N >> M) { memset(V2, 0, sizeof(V2)); memset(vis, 0, sizeof(vis)); memset(DP, 0, sizeof(DP)); C.Clear(N); for (int i = 1; i <= N; ++i) cin >> V[i]; int u, v; for (int i = 1; i <= M; ++i) { cin >> u >> v; C.AddEdge(++u, ++v); } C.Find(); C.BCC(); if (C.Num == 1) { cout << "impossible\n"; continue; } int sum = 0; for (int i = 1; i <= N; ++i) { sum += V[i]; V2[C.ID[i]] += V[i]; } DFS(1); int res = sum; for (int i = 1; i <= C.Num; ++i) { res = min(abs(sum - 2 * DP[i]), res); } cout << res << '\n'; } return 0; }
|