hdu 4638 Group(莫队算法)

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

solution:

莫队算法模板题,只需要自己修改O(1)修改的地方。

#include
#include
#include
#include
using namespace std;
const int maxn = 100050;
int unit;
int a[maxn];
int tmp, ans[maxn];
bool num[maxn];
struct Query
{
    int id, l, r;
    bool operator<(const Query &q)const
    {
        if (l / unit == q.l / unit) return r < q.r;
        return l / unit < q.l / unit;
    }
}query[maxn];
void insert(int x)
{
    if (num[x-1] == 0 && num[x+1] == 0)tmp++;
    else if (num[x-1] && num[x+1])tmp--;
    num[x] = 1;
}
void remove(int x)
{
    if (num[x-1] == 0 && num[x+1] == 0)tmp--;
    else if (num[x-1] == 1 && num[x+1] == 1)tmp++;
    num[x] = 0;
}
int main()
{
    int n, m, t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; ++i)
            scanf("%d", &a[i]);
        unit = (int)sqrt((double)n);
        for (int i = 0; i < m; ++i)
        {
            query[i].id = i;
            scanf("%d%d", &query[i].l, &query[i].r);
        }
        sort(query, query + m);
        int l = 1, r = 0;
        tmp = 0;
        memset(num, 0, sizeof(num));
        for (int i = 0; i query[i].r) remove(a[r--]);
            while (l < query[i].l) remove(a[l++]);
            while (l > query[i].l) insert(a[--l]);
            ans[query[i].id] = tmp;
        }
        for (int i = 0; i 


你可能感兴趣的:(HDU,数据结构,莫队算法)