QOJ.ac

QOJ

ID提交记录ID题目HackerOwner结果提交时间测评时间
#718#460119#8840. Lalo's Lawyer Lostucup-team3215ucup-team3215Failed.2024-07-01 01:48:592024-07-01 01:49:00

詳細信息

Extra Test:

Invalid Input

input:

1
2 2
1 2
2 1

output:


result:

FAIL there can't be any multi-edges (test case 1)

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#460119#8840. Lalo's Lawyer Lostucup-team3215AC ✓131ms34868kbC++201.5kb2024-07-01 01:42:492024-07-01 01:42:50

answer

#include <cstdint>
#include <iostream>
#include <vector>

using namespace std;

constexpr int N = 2e5 + 1;

int d[N], st[N], sz[N], n;
int64_t ans;
vector<int> nei[N], tmp;

void build(int v, int p, int cd) {
  sz[v] = 1;
  d[v] = cd;
  for (auto u: nei[v]) if (u != p) if (!d[u]) {
    build(u, v, cd + 1);
    sz[v] += sz[u];
  }
}

int solve(int v) {
  st[d[v]] = v;
  int r = -1;
  for (auto u: nei[v]) if (d[u] == d[v] + 1) {
    int t = solve(u);
    if (!~t) ans += min(sz[u], n - sz[u]) * 2;
    else if (t != v) r = t;
  } else if (d[u] < d[v] - 1) {
    r = u;
    tmp.push_back(sz[v]);
    for (int i = d[v]; --i > d[u]; ) tmp.push_back(sz[st[i]] - sz[st[i + 1]]);
    tmp.push_back(n - sz[st[d[u] + 1]]);
    int s = 0;
    for (int i = 0; i < tmp.size() / 2; ++i) s += tmp[i];
    for (int i = 0; i < tmp.size() - tmp.size() / 2; ++i) ans += min(s, n - s), s += tmp[i + tmp.size() / 2] - tmp[i];
    for (int i = tmp.size() - tmp.size() / 2; i < tmp.size(); ++i) ans += min(s, n - s), s += tmp[i + tmp.size() / 2 - tmp.size()] - tmp[i];
    tmp.clear();
  }
  return r;
}

int main() {
  cin.tie(0)->sync_with_stdio(0);
  for (int tc = (cin >> tc, tc); tc--; ) {
    int m; cin >> n >> m;
    for (int i = 0; i < m; ++i) {
      int a, b; cin >> a >> b; --a, --b;
      nei[a].push_back(b);
      nei[b].push_back(a);
    }
    build(0, 0, 1);
    solve(0);
    cout << ans / 2 << '\n';
    ans = 0;
    for (int i = 0; i < n; ++i) d[i] = 0, nei[i] = {};
  }
}