P5904 [POI 2014] HOT-Hotels 加强版 题解
Priestess_SLG · · 题解
这是一个不使用长剖的做法。
注意到一组三元点对
考虑使用递归处理子树 - 合并子树信息的结构来解决问题。设当前 DFS 处理的结点是
现在假设需要将
但是注意到当前的中心点从
直接转移时间复杂度是
对树上每个结点都开一个长度为 map 维护其所对应的
vector<int> adj[N];
int dep[N], siz[N], res;
struct Info {
unordered_map<int, int> f, g;
int off_f, off_g;
inline Info() { off_f = off_g = 0; }
} bag[N];
inline int get_f(int id, int d) {
int key = d + bag[id].off_f;
if (bag[id].f.find(key) != bag[id].f.end()) return bag[id].f.find(key)->second;
return 0;
}
inline int get_g(int id, int d) {
int key = d + bag[id].off_g;
if (bag[id].g.find(key) != bag[id].g.end()) return bag[id].g.find(key)->second;
return 0;
}
inline void add_f(int id, int d, int val) { bag[id].f[d + bag[id].off_f] += val; }
inline void add_g(int id, int d, int val) { bag[id].g[d + bag[id].off_g] += val; }
inline int real_f(int id, int key) { return key - bag[id].off_f; }
inline int real_g(int id, int key) { return key - bag[id].off_g; }
inline void chg_cen(int u) { bag[u].g.erase(bag[u].off_g), --bag[u].off_f, ++bag[u].off_g; }
// merge b into a
inline void merge(int a, int b) {
for (auto &[key, cnt] : bag[b].g)
if (real_g(b, key) >= 0) res += cnt * get_f(a, real_g(b, key));
for (auto &[key, cnt] : bag[b].f)
if (real_f(b, key) >= 0) res += cnt * get_g(a, real_f(b, key));
for (auto &[key, cnt] : bag[b].f)
if (real_f(b, key) >= 0) add_g(a, real_f(b, key), cnt * get_f(a, real_f(b, key)));
for (auto &[key, cnt] : bag[b].f) add_f(a, real_f(b, key), cnt);
for (auto &[key, cnt] : bag[b].g) add_g(a, real_g(b, key), cnt);
bag[b].f.clear(), bag[b].g.clear(), bag[b].off_f = bag[b].off_g = 0;
}
inline int dfs(int u, int fa) {
bag[u].f.clear(), bag[u].g.clear(), bag[u].off_f = bag[u].off_g = 0;
add_f(u, 0, 1); int now = u;
for (int &v : adj[u]) if (v != fa) {
int son = dfs(v, u);
chg_cen(son);
if (bag[now].f.size() + bag[now].g.size() < bag[son].f.size() + bag[son].g.size()) swap(now, son);
merge(now, son);
} return now;
}
inline void sol() {
int n; cin >> n;
for (int i = 1; i < n; ++i) {
int a, b; cin >> a >> b;
adj[a].emplace_back(b), adj[b].emplace_back(a);
} dfs(1, 0), cout << res << '\n';
}