题目1:[Codeforces600E]Lomsat gelral
分析:强推入门视频
个人的理解
由于空间有限,处理过的子树的答案不能全都存起来,但是暴力搜索又会tle,所以就有了启发式合并。启发式合并的核心思想就是:通过仅仅保留当前根的重儿子所在的子树的计算结果、重复计算轻儿子,从而大大减少计算量,复杂度 n ∗ l o g n n * logn n∗logn
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//三年竞赛一场空,不开 long long 见祖宗
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
vector<int> g[maxn];
ll num[maxn];
int n;
ll siz[maxn], mson[maxn];
ll cnt[maxn], ans[maxn];
ll nowson, sum, maxcnt;
void dfs1(int u, int fa)
{
siz[u] = 1;
int maxx = 0;
for(int i = 0; i < g[u].size(); i++)
{
int ep = g[u][i];
if(ep == fa) continue;
dfs1(ep, u);
siz[u] += siz[ep];
if(siz[ep] > maxx) maxx = siz[ep], mson[u] = ep;
}
}
int calc(int u, int fa, int val)
{
cnt[num[u]] += val;
if(cnt[num[u]] > maxcnt) maxcnt = cnt[num[u]], sum = num[u];
else if(cnt[num[u]] == maxcnt) sum += num[u];
for(int i = 0; i < g[u].size(); i++)
{
int ep = g[u][i];
if(ep == fa || ep == nowson) continue;
calc(ep, u, val);
}
}
void dfs2(int u, int fa, int flag)
{
for(int i = 0; i < g[u].size(); i++)
{
int ep = g[u][i];
if(ep == fa || ep == mson[u]) continue;
dfs2(ep, u, 0);
}
//此处nowson是为了calc的时候,避免重复计算重儿子
if(mson[u]) dfs2(mson[u], u, 1), nowson = mson[u];
calc(u, fa, 1), nowson = 0;
ans[u] = sum;
if(!flag)//如果u不是重儿子,则全部清空,nowson之前已经是0,就是为了把u的重儿子也清空。
calc(u, fa, -1), sum = 0, maxcnt = 0;
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++) cin >> num[i];
for(int i = 1; i < n; i++)
{
int a, b; cin >> a >> b;
g[a].push_back(b), g[b].push_back(a);
}
dfs1(1, -1);
dfs2(1, -1, 0);
for(int i = 1; i <= n; i++)
printf("%lld%c", ans[i], i == n ? '\n' : ' ');
}