题意:有一棵数,数的每个结点有一个权值,问从结点u到v,满足权值在[a,b]之间的权值和为多少。
分析:数链剖分的模板题啊,比赛的时候竟然没想到(原地装死,将给出的数以节点1为根节点,然后剖分出一些链出来,然后把这些链和线段树对应起来,接着查询就好。
线段树用结构体保存TLE了啊,然后直接用的几个数组= =。
参考代码:
/*树链剖分*/
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define lson rt<<1
#define rson rt<<1|1
typedef long long ll;
const int maxn = 1e5+10;
int n,m,low,high;
int head[maxn],tot;
struct Edge{
int to,next;
}edge[maxn<<1];
ll a[maxn];
int siz[maxn],fa[maxn],son[maxn],dep[maxn];
int p[maxn],fp[maxn],top[maxn],pos;
ll mx,mn;
ll sum[maxn<<2],maxx[maxn<<2],minn[maxn<<2];
void Init()
{
tot = pos = 0;
mem(head,-1);
mem(son,-1);
}
void AddEdge( int u, int v)
{
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
}
void dfs1( int u, int pre, int d)
{
siz[u] = 1;
fa[u] = pre;
dep[u] = d;
for( int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if( v != pre)
{
dfs1(v,u,d+1);
siz[u] += siz[v];
if( son[u] == -1 || siz[v] > siz[son[u]])
son[u] = v;
}
}
}
void dfs2( int u, int tp)
{
top[u] = tp;
p[u] = ++pos;
fp[p[u]] = u;
if( son[u] == -1)
return;
dfs2(son[u],tp);
for( int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if( v != son[u] && v != fa[u])
dfs2(v,v);
}
}
void PushUp( int rt)
{
minn[rt] = min(minn[lson],minn[rson]);
maxx[rt] = max(maxx[lson],maxx[rson]);
sum[rt] = sum[lson]+sum[rson];
}
void Build( int l, int r, int rt)
{
if( l == r)
{
minn[rt] = maxx[rt] = a[fp[l]];
sum[rt] = a[fp[l]];
return;
}
int mid = (l+r)>>1;
Build(l,mid,lson);
Build(mid+1,r,rson);
PushUp(rt);
}
ll Query( int L, int R, int l, int r, int rt)
{
if( L <= l && r <= R && minn[rt] >= mn && maxx[rt] <= mx)
return sum[rt];
if( l == r)
return 0;
int mid = (l+r)>>1;
if( R <= mid)
return Query(L,R,l,mid,lson);
else if( L > mid)
return Query(L,R,mid+1,r,rson);
else
return Query(L,mid,l,mid,lson)+Query(mid+1,R,mid+1,r,rson);
}
ll Find( int u, int v)
{
ll ans = 0;
int t1 = top[u];
int t2 = top[v];
while( t1 != t2)
{
if( dep[t1] < dep[t2])
{
swap(u,v);
swap(t1,t2);
}
ans += Query(p[t1],p[u],1,pos,1);
u = fa[t1];
t1 = top[u];
}
if( dep[u] > dep[v])
swap(u,v);
ans += Query(p[u],p[v],1,n,1);
return ans;
}
int main()
{
while( ~scanf("%d%d",&n,&m))
{
Init();
for( int i = 1; i <= n; i++)
scanf("%lld",&a[i]);
int u,v;
for( int i = 1; i < n; i++)
{
scanf("%d%d",&u,&v);
AddEdge(u,v);
AddEdge(v,u);
}
dfs1(1,0,0);
dfs2(1,1);
Build(1,pos,1);
bool flag = false;
while( m--)
{
scanf("%d%d%lld%lld",&u,&v,&mn,&mx);
if( flag)
printf(" ");
flag = true;
printf("%lld",Find(u,v));
}
puts("");
}
return 0;
}