读入所有query,按右端点递增排序,hash记录当前值的下标,删去(0,t)中相同且非最后一次出现的元素,计算每个query
Best solutions for Problem 3333
Rank | Author | Exe. Time | Exe. Memory | Code Len. | Language | Date |
1 | wxf | 281MS | 3844K | 2342B | G++ | 2012-03-28 14:10:09 |
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
const int maxn=100010;
struct Query
{
int s,t,id;
bool operator < (const Query a) const
{
return this->t<a.t;
}
}q[maxn];
struct TreeArr
{
ll a[maxn];
int n;
void init(int n)
{
this->n=n;
memset(a,0,sizeof(a));
}
void insert(int k,ll v)
{
for(;k<=n;k+=k&-k) a[k]+=v;
}
ll query(int k)
{
ll s=0;
for(;k;k-=k&-k) s+=a[k];
return s;
}
ll query(int s,int t)
{
return query(t)-query(s-1);
}
}ta;
struct Hash
{
int a[140000],b[140000];
int hash(int x)
{
return x&131071;
}
void init()
{
memset(a,-1,sizeof(a));
memset(b,0,sizeof(b));
}
void ins(int x,int k)
{
int z=hash(x);
while(a[z]!=-1&&a[z]!=x) z=hash(z+1);
a[z]=x,b[z]=k;
}
int get(int x)
{
int z=hash(x);
while(a[z]!=-1&&a[z]!=x) z=hash(z+1);
if(a[z]==-1) return -1;
return b[z];
}
}hash;
struct IO_int
{
char ch,buf[20];int i;
void operator >>(int &d)
{
while(ch=getchar(),ch<48||ch>57);d=ch-48;
while(ch=getchar(),ch<58&&ch>47) d=d*10+ch-48;
}
void operator <<(ll d)
{
if(d==0){ puts("0");return;}
for(i=19;d;d/=10) buf[--i]=d%10+48;
puts(buf+i);
}
}io;
int a[maxn];
ll ans[maxn];
int main()
{
int t;io>>t;
while(t--)
{
ta.init(30000);hash.init();
int n;io>>n;
for(int i=0;i<n;i++) io>>a[i];
int m;io>>m;
for(int i=0;i<m;i++)
{
io>>q[i].s;
io>>q[i].t;
q[i].id=i;
}
sort(q,q+m);
int lim=1;
for(int i=0;i<m;i++)
{
while(q[i].t>=lim)
{
int &x=a[lim-1];
int y=hash.get(x);
hash.ins(x,lim);
if(y!=-1) ta.insert(y,-x);
ta.insert(lim,x);
lim++;
}
ans[q[i].id]=ta.query(q[i].s,q[i].t);
}
for(int i=0;i<m;i++) io<<ans[i];
}
return 0;
}