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;
}


發佈了29 篇原創文章 · 獲贊 0 · 訪問量 9355
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章