C++ アルゴリズムとデータ構造のライブラリ
#include "library/graph/tree/centroid.hpp"$O(V)$
int N;
Graph G(N);
vector<int> C = centroid(G);
#pragma once
#include "library/graph/base/graph.hpp"
vector<int> centroid(const Graph &G) {
const int N = (int)G.size();
stack<pair<int, int>> st;
st.emplace(0ll, -1ll);
vector<int> sz(N), par(N);
while (!st.empty()) {
auto p = st.top();
if (sz[p.first] == 0ll) {
sz[p.first] = 1;
for (auto &&[from, to, cost, idx] : G[p.first]) {
if (to != p.second) st.emplace(to, p.first);
}
} else {
for (auto &&[from, to, cost, idx] : G[p.first]) {
if (to != p.second) sz[p.first] += sz[to];
}
par[p.first] = p.second;
st.pop();
}
}
vector<int> ret;
int size = N;
for (int i = 0; i < N; ++i) {
int val = N - sz[i];
for (auto &&[from, to, cost, idx] : G[i]) {
if (to != par[i]) val = max(val, sz[to]);
}
if (val < size) size = val, ret.clear();
if (val == size) ret.emplace_back(i);
}
return ret;
}#line 2 "library/graph/base/edge.hpp"
struct Edge {
int from, to;
long long cost;
int idx;
Edge(int from, int to, long long cost = 1, int idx = -1)
: from(from), to(to), cost(cost), idx(idx) {}
};
#line 3 "library/graph/base/graph.hpp"
struct Graph {
int N;
vector<vector<Edge>> G;
int es;
Graph() = default;
Graph(int N) : N(N), G(N), es(0) {}
const vector<Edge> &operator[](int v) const { return G[v]; }
int size() const { return N; }
void add(int from, int to, long long cost = 1) {
G[from].push_back(Edge(from, to, cost, es++));
}
void add_both(int from, int to, long long cost = 1) {
G[from].push_back(Edge(from, to, cost, es));
G[to].push_back(Edge(to, from, cost, es++));
}
void read(int M, int padding = -1, bool weighted = false,
bool directed = false) {
for (int i = 0; i < M; i++) {
int u, v;
cin >> u >> v;
u += padding, v += padding;
long long cost = 1ll;
if (weighted) cin >> cost;
if (directed) {
add(u, v, cost);
} else {
add_both(u, v, cost);
}
}
}
};
#line 3 "library/graph/tree/centroid.hpp"
vector<int> centroid(const Graph &G) {
const int N = (int)G.size();
stack<pair<int, int>> st;
st.emplace(0ll, -1ll);
vector<int> sz(N), par(N);
while (!st.empty()) {
auto p = st.top();
if (sz[p.first] == 0ll) {
sz[p.first] = 1;
for (auto &&[from, to, cost, idx] : G[p.first]) {
if (to != p.second) st.emplace(to, p.first);
}
} else {
for (auto &&[from, to, cost, idx] : G[p.first]) {
if (to != p.second) sz[p.first] += sz[to];
}
par[p.first] = p.second;
st.pop();
}
}
vector<int> ret;
int size = N;
for (int i = 0; i < N; ++i) {
int val = N - sz[i];
for (auto &&[from, to, cost, idx] : G[i]) {
if (to != par[i]) val = max(val, sz[to]);
}
if (val < size) size = val, ret.clear();
if (val == size) ret.emplace_back(i);
}
return ret;
}