8 条题解

  • 1
    @ 2026-10-6 8:54:14

    提供一种大炮打蚊子方法 用序列线段树或树状数组维护01数组 计算 1~n 总和 时间复杂度 O(n+logn) 建树 O(n),计算 O(log n)

    #include<bits/stdc++.h>
    using namespace std;
    const int inf=0;
    int tree[2000005];
    int a[2000005];
    int n,q;
    inline int f(int a,int b) {
    	return a+b;
    }
    inline void init(int p,int l,int r) {
    	if(l==r) tree[p]=a[l];
    	else {
    		int mid=(l+r)/2;
    		init(p*2,l,mid);
    		init(p*2+1,mid+1,r);
    		tree[p]=f(tree[p*2],tree[p*2+1]);
    	}
    }
    inline void replace(int x,int y) {
    	int posx=1,posy=n,pos=1;
    	while(posx<posy) {
    		if(x>(posx+posy)/2) {
    			posx=(posx+posy)/2+1;
    			pos=pos*2+1;
    		} else {
    			posy=(posx+posy)/2;
    			pos*=2;
    		}
    	}
    	tree[pos]+=y;
    	pos>>=1;
    	while(pos>0) {
    		tree[pos]=f(tree[pos*2],tree[pos*2+1]);
    		pos>>=1;
    	}
    }
    inline int cal(int l,int r,int x,int y,int p) {
    	if(x>=l&&y<=r) return tree[p];
    	else if(x>r||l>y) {
    		return inf;
    	} else {
    		int left = cal(l,r,x,(x+y)/2,p*2);
    		int right = cal(l,r,(x+y)/2+1,y,p*2+1);
    		return f(left,right);
    	}
    }
    int main() {
    	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    	string s;
    	cin>>s;
    	n=s.size();
    	for(int i = 1;i<=n;i++) {
    		a[i]=(s[i-1]=='1');
    	}
    	init(1,1,n);
    	cout<<cal(1,n,1,n,1);
    	return 0;
    }
    

    信息

    ID
    2216
    时间
    1000ms
    内存
    256MiB
    难度
    5
    标签
    递交数
    70
    已通过
    29
    上传者