codeforces 600E. Lomsat gelral 启发式合并

题目链接

给一颗树, 每个节点有初始的颜色值。 1为根节点。定义一个节点的值为, 它的子树中出现最多的颜色的值, 如果有多种颜色出现的次数相同, 那么值为所有颜色的值的和。

每一个叶子节点是一个map, 然后从叶子节点并上去, 注意并的时候把小的map并到大的map里面。

 #include<bits/stdc++.h>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, a, n) for(int i = a; i<n; i++)
#define ull unsigned long long
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-;
const int mod = 1e9+;
const int inf = ;
const int dir[][] = { {-, }, {, }, {, -}, {, } };
const int maxn = 1e5+;
int head[maxn*], color[maxn], num, cnt[maxn], id[maxn];
ll anss[maxn], ans[maxn];
struct node
{
int to, nextt;
}e[maxn*];
void add(int u, int v) {
e[num].to = v, e[num].nextt = head[u], head[u] = num++;
}
map <int, int> m[maxn];
void combine(int &u, int &v) {
if(m[u].size()<m[v].size())
swap(u, v);
for(auto it = m[v].begin(); it!=m[v].end(); it++) {
m[u][it->first] += it->second;
if(m[u][it->first]>cnt[u]) {
cnt[u] = m[u][it->first];
ans[u] = it->first;
} else if(m[u][it->first] == cnt[u]) {
ans[u] += it->first;
}
}
}
void dfs(int u, int fa) {
for(int i = head[u]; ~i; i = e[i].nextt) {
int v = e[i].to;
if(v == fa)
continue;
dfs(v, u);
combine(id[u], id[v]);
}
anss[u] = ans[id[u]];
}
int main()
{
mem1(head);
int n, x, y;
cin>>n;
for(int i = ; i<=n; i++) {
scanf("%d", &x);
id[i] = i;
m[i][x] = ;
cnt[i] = ;
ans[i] = x;
}
for(int i = ; i<n-; i++) {
scanf("%d%d", &x, &y);
add(x, y);
add(y, x);
}
dfs(, );
for(int i = ; i<=n; i++) {
printf("%I64d ", anss[i]);
}
return ;
}
上一篇:Educational Codeforces Round 64 (Rated for Div. 2)题解


下一篇:Ubuntu 14.04 为 root 帐号开启 SSH 登录