题意:给出一棵树,每个节点有一个颜色,求每个节点的子树中颜色数目最多的颜色的和。
思路:如果开n^2的数组记录每个节点子树中出现的颜色的次数那么时空复杂度都会达到O(N^2),无法承受
现在考虑用map来记录每个节点每个颜色出现的数量,用另一个map记录每个结点中出现某个次数的颜色和,然后用启发式合(合并两个结点时遍历小的合并到大的上)并使时间复杂度降到O(n*logn*logn),空间复杂度降为O(n*logn)。
现在证明一下上面的复杂度,因为每次合并时集合至少变为原来两倍,所以每个节点最多被合并到logn个集合中,最多被合并logn次,所以时间复杂度为O(n*logn*logn),空间复杂度为O(n*logn)。
#include <bits/stdc++.h>
#define eps 1e-6
#define LL long long
#define pii pair<int, int>
#define pb push_back
#define mp make_pair
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int MAXN = 100010;
//const int INF = 0x3f3f3f3f;
int n;
map<int, int> cnt[MAXN];
map<int, LL> sumv[MAXN];
vector<int> G[MAXN];
LL ans[MAXN];
void dfs(int u, int fa) {
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (v == fa) continue;
dfs(v, u);
if (cnt[u].size() < cnt[v].size()) {
swap(cnt[u], cnt[v]);
swap(sumv[u], sumv[v]);
}
for (map<int, int>::iterator it = cnt[v].begin(); it != cnt[v].end(); it++) {
sumv[u][cnt[u][it->first]] -= it->first;
cnt[u][it->first] += it->second;
sumv[u][cnt[u][it->first]] += it->first;
}
}
ans[u] = sumv[u].rbegin()->second;
}
int main()
{
//freopen("input.txt", "r", stdin);
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int c;
scanf("%d", &c);
cnt[i][c] = 1;
sumv[i][1] = c;
}
for (int i = 1; i < n; i++) {
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1, 0);
for (int i = 1; i <= n; i++)
printf("%I64d ", ans[i]);
return 0;
}