清点人数

https://loj.ac/problem/10116

题目描述

  有\(n\)节车厢,有k个操作,分为三种:\(①\)询问前m节车厢中的总人数;\(②\)第m节车厢增加x人;\(③\)第m节车厢减少x人。

思路

  维护前缀和,树状数组的模板题,直接套板子即可。

代码

#include <bits/stdc++.h>
using namespace std;
const int N=5e5+10;

int read()
{
	int res=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){res=(res<<3)+(res<<1)+ch-'0';ch=getchar();}
	return res*w;
}
void write(int x)
{
	if(x>10)write(x/10);
	putchar(x%10+'0');
}

int c[N],n;
int lowbit(int x)
{
	return x&-x;
}
void add(int x,int w)
{
	while(x<=n)
	{
		c[x]+=w;
		x+=lowbit(x);
	}
}
int query(int x)
{
	int res=0;
	while(x)
	{
		res+=c[x];
		x-=lowbit(x);
	}
	return res;
}
int main() 
{
	int k;
	n=read();k=read();
	while(k--)
	{
		char ch;
		scanf(" %c",&ch);
		if(ch=='A')
		{
			int m=read();
			write(query(m));
			putchar('\n');
//			printf("%d\n",query(m));
		}
		else
		{
			int m=read(),p=read();
			if(ch=='B')add(m,p);
			else add(m,-p);
		}
	}
}
posted @ 2019-10-28 20:28  fbz  阅读(262)  评论(0编辑  收藏  举报