标签:i++ scan 题意 str sqrt 一个 long log eps
给你一个\(1e5\)的有点权的树,有\(1e5\)个操作:
1.给第\(x\)层的点加上\(y\)
2.求以\(x\)为根的子树的点权和
首先处理出层数为x的所有点
操作2一般都是用dfs序+树状数组/线段树,这题因为它奇怪的题目名字,选择了树状数组
而操作1如果直接暴力的话,复杂度将是\(O(nlogn)\)的,我们想办法把这个复杂度尽量摊到操作2上去
因为只是对层数为\(x\)的增加点权,操作1操作的点数取决于层数为\(x\)的点的个数,我们可以分块
如果操作1要处理的点数超过\(m\),就把m这一层打个标记,否则暴力,复杂度\(O(mlogn)\)
对于操作2,我们\(logn\)得到子树中点数小于\(m\)的层的答案后,从点数大于\(m\)的层中二分算出贡献,复杂度\(O(\frac{n}{m}logn)\)
由于我们是用dfs序来得到每层中的所有点的,所以x的所有同一层的孩子在这里连续,所以可以二分
总复杂度\(O(q(mlogn+\frac{n}{m}))\)
所以\(m=\sqrt{n}\)
复杂度\(O(qlog\sqrt{n}logn)\)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<vector>
#include<map>
#include<functional>
#define fst first
#define sc second
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lc root<<1
#define rc root<<1|1
using namespace std;
typedef double db;
typedef long double ldb;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PI;
typedef pair<ll,ll> PLL;
const db eps = 1e-6;
const int mod = 1e9+7;
const int maxn = 2e5+100;
const int maxm = 2e6+100;
const int inf = 0x3f3f3f3f;
const db pi = acos(-1.0);
int n,q,m;
vector<int>v[maxn],g[maxn],G;
ll tree[maxn];
int tot;
int lowbit(int x){return x&(-x);}
void add(int x, ll c){
for(int i = x; i <= n; i+=lowbit(i))tree[i]+=c;
}
ll sum(int x){
ll ans = 0;
for(int i = x; i; i-=lowbit(i))ans+=tree[i];
return ans;
}
int S[maxn],bg[maxn],ed[maxn];
int dep[maxn];
void dfs(int x, int dp){
bg[x]=++tot;
g[dp].pb(tot);
for(int i = 0; i < (int)v[x].size(); i++){
int y = v[x][i];
dfs(y,dp+1);
}
ed[x]=tot;
}
ll C[maxn];
int main() {
scanf("%d %d", &n, &q);
m = (int)sqrt(n);
for(int i = 1; i < n; i++){
int x, y;
scanf("%d %d", &x, &y);
v[x].pb(y);
}
dfs(1,0);
for(int i = 0; i <= n; i++){
if(g[i].size()>m){
G.pb(i);
}
}
while(q--){
int op,x,y;
scanf("%d %d", &op,&x);
if(op==1){
scanf("%d", &y);
if((int)g[x].size()<=m){
for(int i = 0; i <(int)g[x].size(); i++){
int to = g[x][i];
add(to,y);
}
}
else C[x]+=y;
}
else{
ll ans = sum(ed[x])-sum(bg[x]-1);
for(int i = 0; i < (int)G.size(); i++){
int y = G[i];
int L=-1,R=-1;
int l=0,r=g[y].size()-1;
while(l<=r){
int mid = l+r>>1;
if(g[y][mid]>=bg[x]){
L=mid;
r=mid-1;
}
else l=mid+1;
}
l=0,r=g[y].size()-1;
while(l<=r){
int mid = l+r>>1;
if(g[y][mid]<=ed[x]){
R=mid;
l=mid+1;
}
else r=mid-1;
}
if(L<=R&&L!=-1&&R!=-1)ans+=C[y]*(R-L+1);
}
printf("%lld\n",ans);
}
}
return 0;
}
计蒜客A1998 Ka Chang (分块+dfs序+树状数组)
标签:i++ scan 题意 str sqrt 一个 long log eps
原文地址:https://www.cnblogs.com/wrjlinkkkkkk/p/11686919.html