您的位置:首页 > 其它

HDU(3874)树状数组+离线

2016-01-29 16:18 302 查看
题目大意:和 HDU3333 一样。。。=_= 数据范围有些变化。

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
const int maxn = 55555;
struct node
{
int l, r;
int id;
bool operator < (const node &a)const
{
return r < a.r;
}
}p[maxn << 2];
int n, q;
long long sum[maxn << 2];
long long ans[maxn << 2];
long long a[maxn], b[maxn];
long long tail[maxn];
int lowbit(int x)
{
return x&(-x);
}
void modify(int pos, long long val)
{
for(int i=pos; i<=n; i+=lowbit(i))
{
sum[i] += val;
}
}
long long query(int pos)
{
long long res = 0;
for(int i=pos; i>0; i-=lowbit(i))
{
res += sum[i];
}
return res;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
memset(sum, 0, sizeof sum);
memset(tail, 0, sizeof tail);
scanf("%d", &n);
for(int i=1; i<=n; i++)
{
scanf("%lld", &a[i]);
b[i] = a[i];
}
scanf("%d", &q);
for(int i=1; i<=q; i++)
{
scanf("%d%d", &p[i].l, &p[i].r);
p[i].id = i;
}
sort(b+1, b+1+n);
sort(p+1, p+1+q);
int tot = 1;
for(int i=1; i<=n; i++)
{
int pos = lower_bound(b+1, b+1+n, a[i]) - b;
if(!tail[pos])
{
modify(i, a[i]);
tail[pos] = i;
}
else
{
modify(tail[pos], a[i] * (-1));
modify(i, a[i]);
tail[pos] = i;
}
while(p[tot].r <= i && tot <= q)
{
ans[p[tot].id] = query(i) - query(p[tot].l - 1);
tot++;
}
}
for(int i=1; i<=q; i++)
{
printf("%lld\n", ans[i]);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: