牛客练习赛60-E
dsu on tree
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<bitset>
#include<map>
//#include<regex>
#include<cstdio>
#include <iomanip>
#pragma GCC optimize(2)
#define up(i,a,b) for(int i=a;i<b;i++)
#define dw(i,a,b) for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
//#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
char ch = getchar(); ll x = 0, f = 1;
while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
typedef pair<int, int> pir;
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lrt root<<1
#define rrt root<<1|1
const int N = 1e5 + 10;
int n, k;
ll ai[N],cnt[N];
int num[N], d[N], dfn[N], son[N], sz[N], rk[N];
ll ans[N];
struct eg {
int to, next;
}edge[N<<1];
int head[N << 1];
int eg_cnt = 0;
void adddedge(int u, int v)
{
edge[eg_cnt].next = head[u];
edge[eg_cnt].to = v;
head[u] = eg_cnt++;
}
int st = 0;
void dfs1(int u, int fa,int dep)
{
sz[u] = 1;
d[u] = dep;
dfn[u] = ++st;
rk[st] = u;
for (int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if (v == fa)continue;
dfs1(v, u, dep + 1);
if (son[u] == -1 || sz[son[u]] < sz[v])
son[u] = v;
sz[u] += sz[v];
}
}
void dfs2(int u, int fa,bool is)
{
for (int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if (v == fa || v == son[u])continue;
dfs2(v, u, 0);
}
if (son[u]!=-1)dfs2(son[u], u, 1);
for (int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if (v == fa || v == son[u])continue;
int len = 2 * d[u] + k;
up(i, dfn[v], dfn[v] + sz[v])
{
int dd = d[rk[i]];
int lim = max(0, len - dd);
ans[u] += cnt[lim] + ai[rk[i]] * (num[lim]);
}
up(i, dfn[v], dfn[v] + sz[v])
{
int dd = d[rk[i]];
cnt[dd] += ai[rk[i]];
num[dd]++;
}
}
cnt[d[u]] += ai[u]; num[d[u]]++;
if (!is) {
up(i, dfn[u], dfn[u] + sz[u])
{
cnt[d[rk[i]]] = 0;
num[d[rk[i]]] = 0;
}
}
}
int main()
{
n = read(), k = read();
upd(i, 1, n)ai[i] = read();
memset(head, -1, sizeof(head));
memset(son, -1, sizeof(son));
int x, y;
up(i, 1, n)
{
x = read(), y = read();
adddedge(x, y); adddedge(y, x);
}
dfs1(1, 0, 1);
dfs2(1, 0, 1);
upd(i, 1, n)printf("%lld ", ans[i]);
return 0;
}
橙橙橙