给定一棵有根树,每个节点有权值,求有多少链上的权值和为S,要求链上节点的深度必须单调(即这条链由某个节点出发指向根)。
看到PoPoQQQ学长用类似构造虚树的思想虐了这题,即用栈维护一条长链,然而感觉复杂度不靠谱,于是老老实实写启发式合并了。
启发式合并
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cassert>
#include<ctime>
#include<bitset>
#include<queue>
#include<set>
#define inf (1<<30)
#define INF (1ll<<62)
#define prt(x) cout<<#x<<":"<<x<<" "
#define prtn(x) cout<<#x<<":"<<x<<endl
#define travel(x) for(Edge *e=h[x];e;e=e->n)
using namespace std;
typedef long long ll;
template<class T>void sc(T &x){
x=0;char c;int f=1;
while(c=getchar(),c<48)if(c=='-')f=-1;
do x=x*10+(c^48);
while(c=getchar(),c>47);
x*=f;
}
template<class T>void nt(T x){
if(!x)return;
nt(x/10);
putchar('0'+x%10);
}
template<class T>void pt(T x){
if(x<0)putchar('-'),x=-x;
if(!x)putchar('0');
else nt(x);
}
int n,m;
const int maxn=100005;
int key[maxn];
struct Edge{
Edge *n;
int to;
}*h[maxn];
void ins(int u,int v){
Edge *x=new Edge();
x->n=h[u];x->to=v;
h[u]=x;
}
int b[maxn];
ll ans;
priority_queue<int>*Q[maxn];
void dfs(int x,int f){
key[x]+=key[f];
travel(x)if(e->to!=f){
dfs(e->to,x);
if(!Q[x]||Q[x]->size()<Q[e->to]->size())
Q[x]=Q[e->to];
}
if(!Q[x])Q[x]=new priority_queue<int>;
Q[x]->push(key[x]);
travel(x)if(e->to!=f){
if(Q[x]!=Q[e->to]){
while(!(Q[e->to]->empty())){
int p=Q[e->to]->top();
Q[e->to]->pop();
if(p>=key[x]+m){
if(p==key[x]+m)ans++;
continue;
}
Q[x]->push(p);
}
}
}
while(!(Q[x]->empty())){
int p=Q[x]->top();
if(p>=key[x]+m){
if(p==key[x]+m)ans++;
Q[x]->pop();
}
else break;
}
}
int main(){
// freopen("pro.in","r",stdin);
// freopen("chk.out","w",stdout);
sc(n);sc(m);
for(int i=1;i<=n;i++){
sc(key[i]);
assert(key[i]>0);
}
for(int u,v,i=1;i<n;i++){
sc(u);sc(v);
ins(u,v);ins(v,u);
}
dfs(1,0);
while(!(Q[1]->empty())){
int p=Q[1]->top();
if(p>=m){
if(p==m)ans++;
Q[1]->pop();
}
else break;
}
pt(ans);
return 0;
}