3333

After inventing Turing Tree, 3xian always felt boring when solving problems about intervals, because Turing Tree could easily have the solution. As well, wily 3xian made lots of new problems about intervals. So, today, this sick thing happens again...

Now given a sequence of N numbers A1, A2, ..., AN and a number of Queries(i, j) (1≤i≤j≤N). For each Query(i, j), you are to caculate the sum of distinct values in the subsequence Ai, Ai+1, ..., Aj.

mr 9/3

如何消去之前重复的数字?只要记录下每个数字的前继即可。

代码

#include<iostream>
#include<cstdio>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<map>
using namespace std;

map<long long, long long> last;

long long n,q,T;
long long a[300010],tree[300010],ans[300010];
struct node
{
	long long l,r,num;
}s[300010];

bool cp(node x,node y)
{
	return x.r < y.r;
}

void update(long long x, long long num)
{
	while(x <= n)
	{
		tree[x] += num;
		x       += x & -x;
	}
}

long long add(int x)
{
	long long sum = 0;
	while(x > 0)
	{
		sum += tree[x];
		x   -= x & -x;
	}
	return sum;
}

int main()
{
	freopen("turingtree.in","r",stdin);
	freopen("turingtree.out","w",stdout);
	scanf("%d",&T);
	while(T--)
	{
		memset(ans,0,sizeof(ans));
		memset(a,0,sizeof(a));
		memset(tree,0,sizeof(tree));
		last.clear();
		scanf("%d",&n);
		for(int i = 1; i <= n; i++)
			scanf("%d",&a[i]);
		scanf("%d",&q);
		for(int i=1;i<=q;i++)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			s[i].l = x;
			s[i].r = y;
			s[i].num = i;
		}
		sort(s+1,s+q+1,cp);
		int left = 1;
		for(int k = 1; k <= q; k++)
		{
			for(int i = left; i <= s[k].r; i++)
			{
				update(i, a[i]);
				if(last[a[i]] > 0)
					update(last[a[i]], -a[i]);
				last[a[i]] = i;
			}
			left = s[k].r + 1;
			ans[s[k].num] = add(s[k].r) - 
			                add(s[k].l - 1);
		}
		
		for(int i=1;i<=q;i++)
		{
			printf("%lld\n",ans[i]);
		}
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值