本文主要是介绍旗鼓相当的对手【Dsu on Tree】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接
有很多细节上的东西,还是需要写的细一点,不然很容易wa掉的。
首先,以每个点作为子树的根结点来算贡献很容易发现,所以这里用一个Dsu的方法,使得的复杂度下降至。
然后dsu的过程一定要注意,要先算答案,再放入子树的贡献,当然算答案的时候,我们是要找对应的深度的结点。
于是我们就能算到x的深度为
但是,我们必须保证才能算它的贡献,因为这个等式算出来的deep[x]不保证一定是u的子结点,也有可能会额外的继承不删除的dsu部分的贡献。
是不能保证的,当K比较小的时候deep[id]比较大的时候,容易出事。所以加上判断。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define eps 1e-8
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e5 + 7;
int N, K, head[maxN], cnt, a[maxN];
struct Eddge
{int nex, to;Eddge(int a=-1, int b=0):nex(a), to(b) {}
}edge[maxN << 1];
inline void addEddge(int u, int v)
{edge[cnt] = Eddge(head[u], v);head[u] = cnt++;
}
inline void _add(int u, int v) { addEddge(u, v); addEddge(v, u); }
int siz[maxN], dfn[maxN], tot, rid[maxN], Wson[maxN], deep[maxN] = {0};
void pre_dfs(int u, int fa)
{siz[u] = 1; dfn[u] = ++tot; rid[tot] = u; Wson[u] = -1;int maxx = 0;for(int i=head[u], v; ~i; i=edge[i].nex){v = edge[i].to;if(v == fa) continue;deep[v] = deep[u] + 1;pre_dfs(v, u);siz[u] += siz[v];if(maxx < siz[v]){maxx = siz[v];Wson[u] = v;}}
}
ll have_deep[maxN << 1] = {0}, num_deep[maxN << 1] = {0}, ans[maxN] = {0};
void dfs(int u, int fa, bool keep)
{for(int i=head[u], v; ~i; i=edge[i].nex){v = edge[i].to;if(v == fa || v == Wson[u]) continue;dfs(v, u, false);}if(~Wson[u]){dfs(Wson[u], u, true);}for(int i=head[u], v, id, key; ~i; i=edge[i].nex){v = edge[i].to;if(v == fa || v == Wson[u]) continue;for(int j=dfn[v]; j<dfn[v] + siz[v]; j++){id = rid[j];key = K + (deep[u] << 1) - deep[id];if(key > deep[u]) ans[u] += num_deep[key] * a[id] + have_deep[key];}for(int j=dfn[v]; j<dfn[v] + siz[v]; j++){id = rid[j];num_deep[deep[id]]++;have_deep[deep[id]] += a[id];}}num_deep[deep[u]]++;have_deep[deep[u]] += a[u];if(!keep){for(int i=dfn[u], id; i<dfn[u] + siz[u]; i++){id = rid[i];num_deep[deep[id]]--;have_deep[deep[id]] -= a[id];}}
}
inline void init()
{cnt = 0;for(int i=1; i<=N; i++) head[i] = -1;
}
int main()
{scanf("%d%d", &N, &K);init();for(int i=1; i<=N; i++) scanf("%d", &a[i]);for(int i=1, u, v; i<N; i++){scanf("%d%d", &u, &v);_add(u, v);}pre_dfs(1, 0);dfs(1, 0, true);for(int i=1; i<=N; i++) printf("%lld%c", ans[i], i == N ? '\n' : ' ');return 0;
}
这篇关于旗鼓相当的对手【Dsu on Tree】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!