最基本的敌兵布阵C++实现杭电1166


#include
#include
using namespace std;

#define MAXN 50000
int tree[MAXN*2+1];

void build(int node, int l, int r, int *s)
{
	if(l == r)
	{
		tree[node] = s[l];
		return;
	}
	else
	{
		int m = (l+r)>>1;
		build(node<<1, l, m, s);
		build(node<<1|1, m+1, r, s);
		tree[node] = tree[node<<1] + tree[node<<1|1]; 		
	}
}

void update(int node, int l, int r, int idx, int rt)
{
	if( l == r)
	{
	tree[node] += rt;
	return;
	}
		int m = (l+r)>>1;
		if(idx <= m)
			update(node<<1,l,m,idx,rt);
		else
		{
			update(node<<1|1,m+1,r,idx,rt);
		}
		tree[node] = tree[node<<1]+tree[node<<1|1];
}

int Query(int node, int begin, int end, int l, int r)
{
	if(l<=begin && r>=end)
	{
		return tree[node];
	}
	
		int p1=0,p2=0;
		int m = (begin+end)>>1;
		
		if(l<=m)
			p1 = Query(node<<1,begin,m,l,r);
		if(r>=m+1)
			p2 = Query(node<<1|1,m+1,end,l,r);
		return p1+p2;
	
}





int main()
{
	int T,N,i,j,TEMP;
	int s[MAXN];
	string order;
	cin >> T;
	TEMP = T;
	while(T--)
	{
		cout << "Case " << TEMP - T<<":"<> N;
		for(int i=1;i> s[i];
		}
		 
		build(1,1,N,s);
		
		while(cin >> order)
		{
			if(order == "Add")
			{
				cin >> i;
				cin >> j;
				update(1,1,N,i,j);
			}else if(order == "Sub")
			{
				cin >> i;
				cin >> j;
				update(1,1,N,i,-j);
			}else if(order == "Query")
			{
				cin >> i;
				cin >> j;
				cout << Query(1,1,N,i,j) << endl;
			}else if (order == "End")
			{
				break;
			}
		}
	}
}



你可能感兴趣的:(算法导论学习)