HDU 1806(Frequent values)莫队算法

来源:互联网 发布:淘宝怎么交电话费 编辑:程序博客网 时间:2024/06/04 19:03

这个题呢,当时没有看见这个序列是单调不减的。。。就用莫队算法乱搞。。,居然没有卡我,960ms卡过。。。。
当然了,复杂度是O(n^3/2);对没有log2(n);不然怎么卡过去。。。
那我就说说O(1)转移区间的方法;
a[i]是元素的值;
b[i]为a[i]在[L,R]内出现的次数;
c[i]为[L,R]内出现i次的所有元素之和;

#include<cstdio>#include<cstring>#include<iostream>#include<map>#include<cmath>#include<set>#include<algorithm>#include<functional>using namespace std;const int maxn = 2e5 + 5;int len_block;int a[maxn];int ans[maxn];int b[maxn];int c[maxn];struct node {    int l, r, id, block;    node() {}    node(int l, int r, int id) :l(l), r(r), id(id) {        block = l / len_block + 1;    };}query[maxn];bool cmp(node &a, node &b){    if (a.block == b.block)return a.r < b.r;    return a.block < b.block;}inline bool in(int &ret){    char ch;    bool sgn = false;//正数    ret = 0;    if ((ch = getchar()) == EOF)return false;//EOF    while (ch != '-' && (ch<'0' || ch>'9')) ch = getchar();    if (ch == '-') sgn = true;//负数    else ret = ch - '0';    while (ch = getchar(), ch >= '0'&&ch <= '9') ret = ret * 10 + ch - '0';    if (sgn) ret = -ret;    return true;//当前输入结束}inline void out(int n){    if (n < 0) {        putchar('-'); n = -n;    }    if (n > 9) out(n / 10);    putchar(n % 10 + '0');}inline void add(int pos, int &anscnt){    int &cnt = b[a[pos]];//cnt为当前[L,pos-1]内a[pos]出现的次数;    c[cnt] -= cnt*a[pos];//因为,现在a[pos]出现了cnt+1次;那么更新c[cnt]的sum;    cnt++;    c[cnt] += cnt*a[pos];//a[pos]出现了cnt+1次更新c[cnt+1]的sum    anscnt = max(cnt, anscnt);}inline void dele(int pos, int &anscnt){    int &cnt = b[a[pos]];    c[cnt] -= cnt* a[pos];    if (c[cnt] == 0 && anscnt == cnt) anscnt--;//如果此层元素为空,那么就是说,cnt层已经被删除了;    cnt--;    c[cnt] += cnt*a[pos];}int main(){    int n, q;    while (in(n),n)    {        if (n == 0)break;        in(q);        len_block = int(sqrt(n))+10;        memset(b, 0, sizeof b);        memset(c, 0, sizeof c);        for (int i = 1; i <= n; i++) {             in(a[i]);            a[i] += maxn / 2;        }        for (int i = 1; i <= q; i++) {            int l, r;            in(l);             in(r);            query[i] = node(l, r, i);        }        sort(query + 1, query + q + 1, cmp);        int l = 1, r = 1;        b[a[1]] = 1;        c[b[a[1]]] = a[1];        int anscnt = 1;        for (int i = 1; i <= q; i++) {            node qr = query[i];            while (r < qr.r) add(++r,anscnt);            while (l > qr.l) add(--l, anscnt);            while (r > qr.r) dele(r--, anscnt);            while (l < qr.l) dele(l++, anscnt);            ans[qr.id] = anscnt;        }        for (int i = 1; i <= q; i++)        {            out(ans[i]);            putchar('\n');        }    }    return 0;}
原创粉丝点击