hdu 4638 Group

来源:互联网 发布:华艺服装淘宝店 编辑:程序博客网 时间:2024/06/08 01:20

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
题意:
求将给定区间中的数按照其值是否连续分组,最少可以分成几组;

思路:
主要的点在于对于插入一个数a[k],如果a[k]+1和a[k]-1都已存在这个区间中那个答案减一,如果二者皆不存在,那么答案加一;

#include <bits/stdc++.h>using namespace std;const int maxn=1000009;int a[maxn];int ans[maxn];int vis[maxn];struct query{    int l,r,id,pos;} q[maxn];int cmp(query a,query b){    return a.pos==b.pos?a.r<b.r:a.pos<b.pos;}int main(){    int t;    scanf("%d",&t);    while(t--)    {        memset(vis,0,sizeof vis);        int n,m;        scanf("%d%d",&n,&m);        for(int i=1; i<=n; i++)            scanf("%d",&a[i]);        int block=sqrt(n);        for(int i=0; i<m; i++)        {            scanf("%d%d",&q[i].l,&q[i].r);            q[i].id=i;            q[i].pos=q[i].l/block;        }        sort(q,q+m,cmp);        int L=1,R=1;        int res=1;        vis[a[1]]=1;        for(int i=0; i<m; i++)        {            for(int k=q[i].l; k<L; k++)            {                if(vis[a[k]-1]&&vis[a[k]+1])                    res--;                else if(!vis[a[k]-1]&&!vis[a[k]+1])                    res++;                vis[a[k]]=1;            }            for(int k=R+1; k<=q[i].r; k++)            {                if(vis[a[k]-1]&&vis[a[k]+1])                    res--;                else if(!vis[a[k]-1]&&!vis[a[k]+1])                    res++;                vis[a[k]]=1;            }            for(int k=L; k<q[i].l; k++)            {                if(!vis[a[k]-1]&&!vis[a[k]+1])                    res--;                else if(vis[a[k]-1]&&vis[a[k]+1])                    res++;                vis[a[k]]=0;            }            for(int k=q[i].r+1; k<=R; k++)            {                if(!vis[a[k]-1]&&!vis[a[k]+1])                    res--;                else if(vis[a[k]-1]&&vis[a[k]+1])                    res++;                vis[a[k]]=0;            }            L=q[i].l,R=q[i].r,ans[q[i].id]=res;        }        for(int i=0; i<m; i++)            printf("%d\n",ans[i]);    }    return 0;}
原创粉丝点击