Atcoder：AGC004F Namori

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn(1e5 + 5);

struct Edge {  int to, next;  };

int n, m, first[maxn], cnt, sum[maxn], fa[maxn], dsu[maxn], deep[maxn], a, b, ans, val[maxn];
Edge edge[maxn << 1];

inline int Find(int x) {  return (dsu[x] ^ x) ? dsu[x] = Find(dsu[x]) : x;  }

inline void Add(int u, int v) {
edge[cnt] = (Edge){v, first[u]}, first[u] = cnt++;
edge[cnt] = (Edge){u, first[v]}, first[v] = cnt++;
}

void Dfs(int u, int ff, int d) {
int e, v;
sum[u] = d;
for (e = first[u]; ~e; e = edge[e].next)
if ((v = edge[e].to) ^ ff) {
deep[v] = deep[u] + 1;
fa[v] = u, Dfs(v, u, -d);
sum[u] += sum[v];
}
}

int main() {
int i, u, v, len = 1;
memset(first, -1, sizeof(first));
scanf("%d%d", &n, &m);
if (n & 1) return puts("-1"), 0;
for (i = 1; i <= n; ++i) dsu[i] = i;
for (i = 1; i <= m; ++i) {
scanf("%d%d", &u, &v);
if (Find(u) ^ Find(v)) Add(u, v), dsu[Find(u)] = Find(v);
else a = u, b = v;
}
if (!a) {
Dfs(1, 0, 1);
if (sum[1]) return puts("-1"), 0;
}
else {
Dfs(a, 0, 1);
if (deep[b] & 1) {
if (sum[a]) return puts("-1"), 0;
for (i = b; i ^ a; i = fa[i]) val[++len] = sum[i], sum[i] = 0;
sort(val + 1, val + len + 1), v = val[(len + 1) >> 1];
for (i = 1; i <= len; ++i) ans += abs(val[i] - v);
}
else {
if (sum[a] & 1) return puts("-1"), 0;
v = sum[a] >> 1, ans = abs(v), sum[a] = 0;
for (i = b; i ^ a; i = fa[i]) sum[i] -= v;
}
}
for (i = 1; i <= n; ++i) ans += abs(sum[i]);
printf("%d\n", ans);
return 0;
}

posted @ 2019-03-02 16:44  Cyhlnj  阅读(234)  评论(0编辑  收藏  举报