1. 程式人生 > >Alyona and a tree CodeForces - 739B (線段樹合並)

Alyona and a tree CodeForces - 739B (線段樹合並)

struct tchar n) scan ces 給定 oid a* ||

大意: 給定有根樹, 每個點$x$有權值$a_x$, 對於每個點$x$, 求出$x$子樹內所有點$y$, 需要滿足$dist(x,y)<=a_y$.

剛開始想錯了, 直接打線段樹合並了.....因為範圍是$long \space long$常數極大, 空間很可能會被卡, 不過竟然過了. 實際上本題每個點對樹鏈上的貢獻是單調的, 直接二分就行了

放一下線段樹合並代碼

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc tr[o].l
#define rc tr[o].r
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl ‘\n‘
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
//head




const int N = 2e5+10;
int n, tot, a[N], rt[N], ans[N];
struct _ {int to,w;};
vector<_> g[N];
ll d[N], L, R;
struct {int l,r,sum;} tr[N<<6];
typedef int&& dd;

int merge(int x, int y) {
	if (!x||!y) return x+y;
	tr[x].l=merge(tr[x].l,tr[y].l);
	tr[x].r=merge(tr[x].r,tr[y].r);
	tr[x].sum+=tr[y].sum;
	return x;
}
int query(int o, ll l, ll r, ll ql, ll qr) {
	if (!o||ql<=l&&r<=qr) return tr[o].sum;
	int ans = 0;
	if (mid>=ql) ans+=query(ls,ql,qr);
	if (mid<qr) ans+=query(rs,ql,qr);
	return ans;
}
void update(int &o, ll l, ll r, ll x) {
	if (!o) o=++tot;
	++tr[o].sum;
	if (l==r) return;
	if (mid>=x) update(ls,x);
	else update(rs,x);
}
void dfs(int x) {
	for (auto &&e:g[x]) d[e.to]=d[x]+e.w,dfs(e.to);
	L = min(L, d[x]), R = max(R, d[x]);
	L = min(L, d[x]-a[x]), R = max(R, d[x]-a[x]);
}
void solve(int x) {
	for (auto &&e:g[x]) { 
		solve(e.to); rt[x]=merge(rt[x],rt[e.to]);
	}
	ans[x] = query(rt[x],L,R,L,d[x]);
	update(rt[x],L,R,d[x]-a[x]);
}

int main() {
	int &&t = n;
	scanf("%d", &n);
	REP(i,1,n) scanf("%d", a+i);
	REP(i,2,n) {
		int f, w;
		scanf("%d%d", &f, &w);
		g[f].pb({i,w});
	}
	dfs(1),solve(1);
	REP(i,1,n) printf("%d ", ans[i]);hr;
}

Alyona and a tree CodeForces - 739B (線段樹合並)