There are n men ,every man has an ID(1…n).their ID is unique. Whose ID is i and i-1 are friends, Whose ID is i and i+1 are friends. These n men stand in line. Now we select an interval of men to make some group. K men in a group can create K*K value. The value of an interval is sum of these value of groups. The people of same group’s id must be continuous. Now we chose an interval of men and want to know there should be how many groups so the value of interval is max.
Input
First line is T indicate the case number.
For each case first line is n, m(1<=n ,m<=100000) indicate there are n men and m query.
Then a line have n number indicate the ID of men from left to right.
Next m line each line has two number L,R(1<=L<=R<=n),mean we want to know the answer of [L,R].
Output
For every query output a number indicate there should be how many group so that the sum of value is max.
Sample Input
1
5 2
3 1 2 5 4
1 5
2 4
Sample Output
1
2
线段树离线处理。求区间l~r之间有多少组连续的值。
对于当前的值vi,我们判断在它之前v[vi-1]和v[vi+1]有没有出现过。把他们的位置更新为-1,把vi的位置更新为1。在套线段树求区间和就可以了。
代码如下:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxx=1e5+100;
struct node{
int l;
int r;
int sum;
}p[maxx<<2];
struct Node{
int l;
int r;
int id;
bool operator<(const Node &a)const{
return a.r>r;
}
}v[maxx];
int a[maxx],ans[maxx];
int n,m;
inline void pushup(int cur)
{
p[cur].sum=p[cur<<1].sum+p[cur<<1|1].sum;
}
inline void build(int l,int r,int cur)
{
p[cur].l=l;
p[cur].r=r;
p[cur].sum=0;
if(l==r) return ;
int mid=l+r>>1;
build(l,mid,cur<<1);
build(mid+1,r,cur<<1|1);
}
inline void update(int pos,int v,int cur)
{
int L=p[cur].l;
int R=p[cur].r;
if(L==R)
{
p[cur].sum+=v;
return ;
}
int mid=L+R>>1;
if(pos<=mid) update(pos,v,cur<<1);
else update(pos,v,cur<<1|1);
pushup(cur);
}
inline int query(int l,int r,int cur)
{
int L=p[cur].l;
int R=p[cur].r;
if(l<=L&&R<=r) return p[cur].sum;
int mid=L+R>>1;
if(r<=mid) return query(l,r,cur<<1);
else if(l>mid) return query(l,r,cur<<1|1);
else return query(l,mid,cur<<1)+query(mid+1,r,cur<<1|1);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<=m;i++) scanf("%d%d",&v[i].l,&v[i].r),v[i].id=i;
build(1,n,1);
sort(v+1,v+1+m);
map<int,int>mp;int j=1;
for(int i=1;i<=n&&j<=m;i++)
{
if(a[i]-1>=1&&mp[a[i]-1]) update(mp[a[i]-1],-1,1);
if(a[i]+1<=n&&mp[a[i]+1]) update(mp[a[i]+1],-1,1);
mp[a[i]]=i;update(i,1,1);
for(;j<=m&&v[j].r==i;j++) ans[v[j].id]=query(v[j].l,v[j].r,1);
}
for(int i=1;i<=m;i++) printf("%d\n",ans[i]);
}
return 0;
}
努力加油a啊,(o)/~