码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 3279 Ants(线段树)

时间:2015-08-09 18:56:39      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

Ants

Time Limit: 2 Seconds      Memory Limit: 32768 KB

echo is a curious and clever girl, and she is addicted to the ants recently.

She knows that the ants are divided into many levels depends on ability, also, she finds the number of each level will change.

Now, she will give two kinds of operations as follow :

First, "p a b", the number of ants in level a change to b.

Second, "q x", it means if the ant‘s ability is rank xth in all ants, what level will it in?

Input

There are multi-cases, and you should use EOF to check whether it is in the end of the input. The first line is an integer n, means the number of level. (1 <= n <= 100000). The second line follows n integers, the ith integer means the number in level i. The third line is an integer k, means the total number of operations. Then following k lines, each line will be "p a b" or "q x", and 1 <= x <= total ants, 1 <= a <= n, 0 <= b. What‘s more, the total number of ants won‘t exceed 2000000000 in any time.

Output

Output each query in order, one query each line.

Sample Input

3
1 2 3
3
q 2
p 1 2
q 2

Sample Output

2
1

Author: Lin, Yue

Source: ZOJ Monthly, December 2009

给出每个等级的数目,后面m个操作,q查询排名x在第几个等级,p a b,把a等级的数目改为b

ac代码

#include<stdio.h>
#include<string.h>
int node[100010<<2];
void build(int l,int r,int tr)
{
	if(l==r)
	{
		scanf("%d",&node[tr]);
		return;
	}
	int mid=(l+r)>>1;
	build(l,mid,tr<<1);
	build(mid+1,r,tr<<1|1);
	node[tr]=node[tr<<1]+node[tr<<1|1];
}
void update(int pos,int val,int l,int r,int tr)
{
	if(l==r)
	{
		node[tr]=val;
		return;
	}
	int mid=(l+r)>>1;
	if(pos<=mid)
		update(pos,val,l,mid,tr<<1);
	else
		update(pos,val,mid+1,r,tr<<1|1);
	node[tr]=node[tr<<1]+node[tr<<1|1];
}
int query(int val,int l,int r,int tr)
{
	if(l==r)
	{
		return l;
	}
	int mid=(l+r)>>1;
	if(val<=node[tr<<1])
		query(val,l,mid,tr<<1);
	else
		query(val-node[tr<<1],mid+1,r,tr<<1|1);
}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		int i;
		memset(node,0,sizeof(node));
		build(1,n,1);
		int m;
		scanf("%d",&m);
		while(m--)
		{
			char s[2];
			scanf("%s",s);
			if(s[0]=='q')
			{
				int x;
				scanf("%d",&x);
				int ans=query(x,1,n,1);
				printf("%d\n",ans);
			}
			else
			{
				int a,b;
				scanf("%d%d",&a,&b);
				update(a,b,1,n,1);
			}
		}
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

ZOJ 3279 Ants(线段树)

标签:

原文地址:http://blog.csdn.net/yu_ch_sh/article/details/47377651

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!