题目描述:
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.
输入
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].
输出
For every query output a number indicate there should be how many group so that the sum of value is max.
样例输入:
1
5 2
3 1 2 5 4
1 5
2 4
样例输出:
1
2
莫队算法,对于本蒟蒻而言,比较神奇
本题应该算是莫队算法的基础题目
通过将询问合理的安排,达到减少时间复杂度的效果
简单来说,就是将询问分块+排序
代码如下:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
using namespace std;
int a[100005];
const int maxn=100010;
long long num[maxn];
long long ans[maxn];
long long res;
int k;
struct node
{
int l,r,id,pos;
}feng[maxn];
bool cmp(node x,node y)
{
return x.pos<y.pos||x.pos==y.pos&&x.r<y.r;
}
void reduce(int temp)
{
if(num[temp-1]&&num[temp+1])res++;
else if(!num[temp-1]&&!num[temp+1])res--;
num[temp]=0;
}
void add(int temp)
{
if(num[temp+1]&&num[temp-1])res--;
else if(!num[temp-1]&&!num[temp+1])res++;
num[temp]=1;
}
int main()
{
int n,m,t,l,r,temp;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
int i,j;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
k=sqrt((double)n);
for(i=0;i<m;i++)
{
scanf("%d%d",&feng[i].l,&feng[i].r);
feng[i].id=i;
feng[i].pos=feng[i].l/k;
}
sort(feng,feng+m,cmp);
memset(num,0,sizeof(num));
l=1;
r=0;
res=0;
for(i=0;i<m;i++)
{
while(r>feng[i].r)
{
temp=a[r];
reduce(temp);
r--;
}
while(r<feng[i].r)
{
r++;
temp=a[r];
add(temp);
}
while(l<feng[i].l)
{
temp=a[l];
reduce(temp);
l++;
}
while(l>feng[i].l)
{
l--;
temp=a[l];
add(temp);
}
ans[feng[i].id]=res;
}
for(i=0;i<m;i++)
{
printf("%lld\n",ans[i]);
}
}
return 0;
}