HDU3874Necklace(树状数组+离线操作)

时间:2024-01-16 15:35:56

此题的大意思说有一串珠子,每个珠子都有自己的欣赏值value,现在给你一串珠子每个的欣赏值,并给出一些询问,查询某个区间内部总欣赏值是多少,但是有一个约定就是如果这个区间内部有两个珠子的欣赏值是一样的,那么他们就视为一个。

其实也就是求某个区间内部不同的数的和。

这里学到了一个比较好的方法,那就是离线操作。根据我的理解,离线操作就是为了解决在询问中所遇到的矛盾的,它在本题上的实现就是先将查询排序,比如按照每个查询的右端点的升序排序,这样的话每次查询一个区间的时候,我们就把它的右端点到上一个查询的右端点之间且在之前已经出现过了相同价值的点删除掉,这样的话就可以保证对后面的查询不会有影响。

具体实现就是用一个last[]数组保存每一个value值最初出现的位置,再用一个Right保存上次扫描的区间的右端点(初始化为1,下图中的R表示),每次查询一个区间的和时,先按照Right到这个区间右端点扫描一遍,如果当中有一个value值上次出现的位置不在它自己的位置时,如下图第2个1之前出现的位置L[1]=1,那么我们就把第一个1从树状数组里面去掉,然后同时更新L[1]为当前位置L[1]=2.这样一来当前的1之前就可以保证没有重复的1。而且下次找到另外一个1时,也只会删除位置为2的1.

同时我们还要更新Right值为当前区间的右端点(因为之前区间已经没有重复的了)

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAwsAAAFBCAIAAAC3mKTOAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABD6SURBVHhe7dy/qiTXtQfgeZAbmRv7AZRMOoFxoGcQg3GgxPgRJjEIdFOHCgaMA+NEmVAisIOTGmOMDEIgbnIdTOJwbvec+tfrdPV07Vp9eteu72MFouf0rr131+z1U3efefEeAIBTEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIAQCQhAQBEEhIA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EBAAQSUgAAJGEBAAQSUgAAJGEBAAQSUgAAJGEBAAQSUgAAJGEBABw6v37/wfskXS9RRfodQAAAABJRU5ErkJggg==" alt="" width="597" height="245" />

同时,由于是按照右端点的升序排列,所以可能会用到之前的1或者不用,用的话同样保证了只有1个1,所以这样排序是对的

 #include <stdio.h>
#include <string.h>
#include <algorithm>
#define mem(a) memset(a,0,sizeof(a))
#define MAX(a , b) ((a) > (b) ? (a) : (b))
using namespace std; struct QUERY
{
int a,b;
int index;
}query[];
__int64 c[], ans[];
int last[], value[], N, M, T; int cmp(QUERY x, QUERY y)
{
return x.b < y.b;
} int lowbit(int x)
{
return x & (-x);
} __int64 getSum(int k)
{
__int64 sum = ;
while(k>=)
{
sum += c[k];
k -= lowbit(k);
}
return sum;
} void edit(int k, int val)
{
while(k<=N)
{
c[k] += val;
k += lowbit(k);
}
} int main()
{
while(~scanf("%d", &T))while(T--)
{
mem(query); mem(c);
mem(last); mem(ans);
mem(value);
scanf("%d", &N);
for(int i=;i<=N;i++)
{
scanf("%d", &value[i]);
edit(i, value[i]);
if(!last[value[i]]) last[value[i]] = i;
}
scanf("%d", &M);
for(int i=;i<=M;i++)
{
scanf("%d%d", &query[i].a, &query[i].b);
query[i].index = i;
}
sort(query+, query+M+, cmp);
int lastRight = ;
for(int i = ; i <= M; i ++)
{
for(int j = lastRight; j <= query[i].b; j ++)
{
if(last[value[j]] != j)
{
edit(last[value[j]], -value[j]);
last[value[j]] = j;
}
}
lastRight = query[i].b;
ans[query[i].index] = getSum(query[i].b) - getSum(query[i].a-);
}
for(int i=;i<=M;i++)
{
printf("%I64d\n", ans[i]);
}
}
return ;
}