跳到正文

个人记录

2022/4/15 练习情况

MattL约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年4月20日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 3 分钟

版本

  1. v1当前

2022/4/15 练习情况

P2068 统计和 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

树状数组

  • 思路:几乎就是【模板】树状数组1
  • 注意:long long
C++
#include <bits/stdc++.h>
using namespace std;
#define lowbit(x) (x&-x)
#define int long long
const int N=5e6+100;
int X,Y,t[N],n,m,tt;
char opt;
void add(int x,int val)
{
	while(x<=n)
		t[x]+=val,x+=lowbit(x);
}
int sum(int x,int cnt=0)
{
	while(x)
		cnt+=t[x],x-=lowbit(x);
	return cnt;
}
signed main()
{
    cin>>n>>m;
    while(m--)
    {
    	cin>>opt>>X>>Y;
    	if(opt=='x')
    		add(X,Y);
    	else
    		cout<<sum(Y)-sum(X-1)<<endl;
	}
    return 0;
}

P5057 [CQOI2006]简单题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

树状数组

  • 思路:几乎就是【模板】树状数组2,把 + 和 - 都变成 ^ 即可
  • 注意由于维护的是差分,所以查询时时输要输出前缀和而不是单点
C++
#include <bits/stdc++.h>
using namespace std;
#define lowbit(x) (x&-x)
#define int long long
const int N=1e5+100;
int X,Y,n,opt,m,tt;
bool t[N];
void add(int x)
{
	while(x<=n)
		t[x]=t[x]^1,x+=lowbit(x);
}
bool sum(int x,bool cnt=0)
{
	while(x)
		cnt^=t[x],x-=lowbit(x);
	return cnt;
}
signed main()
{
    cin>>n>>m;
    while(m--)
    {
    	cin>>opt;
    	if(opt==1)
    		cin>>X>>Y,add(X),add(Y+1);
    	else
    		cin>>X,cout<<sum(X)<<endl;
	}
    return 0;
}
原文