HDU-3874 Necklace 线段树+离线

  题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3874

  比较简单的题,题意也好懂。

  先O(n)求每个数左边第一次出现的与他相同的数的位置l[i]。对询问按照y从小大排序,然后按照从左到右的顺序来跟新点,当前点为i,那么删掉l[i],加入点i,然后遇到询问求和。

 //STATUS:C++_AC_2593MS_10024KB
#include <functional>
#include <algorithm>
#include <iostream>
//#include <ext/rope>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
//using namespace __gnu_cxx;
//define
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1.0)
//typedef
typedef __int64 LL;
typedef unsigned __int64 ULL;
//const
const int N=,M=;
const int INF=0x3f3f3f3f;
const int MOD=,STA=;
const LL LNF=1LL<<;
const double EPS=1e-;
const double OO=1e15;
const int dx[]={-,,,};
const int dy[]={,,,-};
const int day[]={,,,,,,,,,,,,};
//Daily Use ...
inline int sign(double x){return (x>EPS)-(x<-EPS);}
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T lcm(T a,T b,T d){return a/d*b;}
template<class T> inline T Min(T a,T b){return a<b?a:b;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
template<class T> inline T Min(T a,T b,T c){return min(min(a, b),c);}
template<class T> inline T Max(T a,T b,T c){return max(max(a, b),c);}
template<class T> inline T Min(T a,T b,T c,T d){return min(min(a, b),min(c,d));}
template<class T> inline T Max(T a,T b,T c,T d){return max(max(a, b),max(c,d));}
//End struct Node{
int a,b,id;
bool operator < (const Node& a)const {
return b<a.b;
}
}q[M];
LL sum[N<<],ans[M];
int num[N],l[N],la[];
int T,n,m; void update(int l,int r,int rt,int w,int val)
{
if(l==r){
sum[rt]=val;
return;
}
int mid=(l+r)>>;
if(w<=mid)update(lson,w,val);
else update(rson,w,val);
sum[rt]=sum[rt<<]+sum[rt<<|];
} LL query(int l,int r,int rt,int L,int R)
{
if(L<=l && r<=R){
return sum[rt];
}
int mid=(l+r)>>;
LL ret=;
if(L<=mid)ret+=query(lson,L,R);
if(R>mid)ret+=query(rson,L,R);
return ret;
} int main()
{
// freopen("in.txt","r",stdin);
int i,j,k;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
mem(la,);
for(i=;i<=n;i++){
scanf("%d",&num[i]);
l[i]=la[num[i]];
la[num[i]]=i;
}
scanf("%d",&m);
for(i=;i<m;i++){
scanf("%d%d",&q[i].a,&q[i].b);
q[i].id=i;
}
sort(q,q+m);
mem(sum,);k=;
for(i=;i<=n;i++){
if(l[i]){
update(,n,,l[i],);
}
update(,n,,i,num[i]);
for(;q[k].b==i && k<m;k++){
ans[q[k].id]=query(,n,,q[k].a,q[k].b);
}
}
for(i=;i<m;i++){
printf("%I64d\n",ans[i]);
}
}
return ;
}
上一篇:Spring MVC过滤器-委派过滤器代理(DelegatingFilterProxy)


下一篇:链队列之C++实现