Problem Description
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
题意:1—n的排列,给定一个区间,找出一种分组方法,组最少(每组里面的数要连续)
思路:如果一个新出现的数字x,x-1和x+1都已经存在,那么就从两个组凑成一个连续数字的组;如果一个新出现的数字,x-1和x+1都不存在,x就单独一组,总组数+1;对消失的数字同理
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<vector>
using namespace std;
int k,n,m;
struct node
{
int l,r,id;
bool operator <(const node &a)const
{
if(a.l/k==l/k)
{
return r<a.r;
}
return a.l/k<l/k;
}
}ask[100005];
int answer[100005];
int a[100005],T;
int ans;
int num[100005];
int main()
{
scanf("%d",&T);
while(T--)
{
memset(a,0,sizeof(a));
memset(num,0,sizeof(num));
scanf("%d%d",&n,&m);
k=sqrt(n);
ans=0;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&ask[i].l,&ask[i].r);
ask[i].id=i;
}
sort(ask+1,ask+1+m);
int l=1,r=0;
for(int i=1;i<=m;i++)
{
int L=ask[i].l;
int R=ask[i].r;
while(r<R)
{
r++;
if(num[a[r]-1]==0&&num[a[r]+1]==0&&num[a[r]]==0) ans++;
if(num[a[r]-1]!=0&&num[a[r]+1]!=0&&num[a[r]]==0) ans--;
num[a[r]]++;
}
while(r>R)
{
num[a[r]]--;
if(num[a[r]]==0&&num[a[r]-1]!=0&&num[a[r]+1]!=0) ans++;
if(num[a[r]]==0&&num[a[r]-1]==0&&num[a[r]+1]==0) ans--;
r--;
}
while(l>L)
{
l--;
if(num[a[l]]==0&&num[a[l]-1]==0&&num[a[l]+1]==0) ans++;
if(num[a[l]]==0&&num[a[l]-1]!=0&&num[a[l]+1]!=0) ans--;
num[a[l]]++;
}
while(l<L)
{
num[a[l]]--;
if(num[a[l]-1]!=0&&num[a[l]+1]!=0&&num[a[l]]==0) ans++;
if(num[a[l]-1]==0&&num[a[l]+1]==0&&num[a[l]]==0) ans--;
l++;
}
answer[ask[i].id]=ans;
}
for(int i=1;i<=m;i++)
printf("%d\n",answer[i]);
}
return 0;
}