【Codeforces700D】Huffman Coding on Segment

Keywords: less

Title:
Give you n numbers, and ask the shortest length of the number in the interval [l,r] encoded by binary Huffman.

I tore and roasted the tree for about a long time. Then look at the problem and tell me it's Moqu Team! __________ (wtf?)
According to the number of occurrences, it can be divided into those greater than n_and those less than or equal to n_. If a merger is smaller than or equal to a merger with no brain, it is better to join a priority queue with a merger larger than N and then select two mergers smaller than n after the final processing.
Time complexity O(nn logn), can pass.

#include <bits/stdc++.h>
#define gc getchar()
#define ll long long
#define N 100009
using namespace std;
int n,a[N],Q,limit,block[N],num[N],number[N],Ans[N],Number[N];
vector<int> Big;
struct qry
{
    int l,r,pos;
    bool operator <(const qry &rhs)
    {
        return block[l]<block[rhs.l]||(block[l]==block[rhs.l]&&r<rhs.r);
    }
}q[N];
int read()
{
    int x=1;
    char ch;
    while (ch=gc,ch<'0'||ch>'9') if (ch=='-') x=-1;
    int s=ch-'0';
    while (ch=gc,ch>='0'&&ch<='9') s=s*10+ch-'0';
    return x*s;
}
void add(int x,int y)
{
    number[num[x]]--;
    num[x]+=y;
    number[num[x]]++;
}
int calc()
{
    priority_queue<int,vector<int>,greater<int> > qq;
    for (int i=0;i<(int)Big.size();i++)
        if (num[Big[i]]>limit) qq.push(num[Big[i]]);
    for (int i=1;i<=limit;i++) Number[i]=number[i];
    int ret=0,last=0;
    for (int i=1;i<=limit;i++)
        if (Number[i])
        {
            if (last)
            {
                Number[i]--,ret+=last+i;
                if (last+i<=limit) Number[last+i]++;
                else qq.push(last+i);
                last=0;
            }
            if (Number[i]&1)
                Number[i]--,last=i;
            ret+=Number[i]*i;
            if (2*i<=limit) Number[2*i]+=Number[i]/2;
            else
                for (int j=1;j<=Number[i]/2;j++) qq.push(i*2);
        }
    if (last) qq.push(last);
    while ((int)qq.size()>1)
    {
        int x1=qq.top();
        qq.pop();
        int x2=qq.top();
        qq.pop();
        ret+=x1+x2,qq.push(x1+x2);
    }
    return ret;
}
int main()
{
    n=read();
    limit=sqrt(n);
    for (int i=1;i<=n;i++)
    {
        a[i]=read();
        if ((++num[a[i]])==limit) Big.push_back(a[i]);
        if (num[a[i]]==1) number[0]++; 
    }
    memset(num,0,sizeof(num));
    Q=read();
    for (int i=1;i<=Q;i++)
        q[i].l=read(),q[i].r=read(),q[i].pos=i;
    for (int i=1;i<=n;i++)
        block[i]=i/limit+1;
    sort(q+1,q+Q+1);
    int l=1,r=0;
    for (int i=1;i<=Q;i++)
    {
        while (r<q[i].r) add(a[++r],1);
        while (l>q[i].l) add(a[--l],1);
        while (r>q[i].r) add(a[r--],-1);
        while (l<q[i].l) add(a[l++],-1);
        Ans[q[i].pos]=calc(); 
    }
    for (int i=1;i<=Q;i++)
        printf("%d\n",Ans[i]);
    return 0;
}

Posted by postalservice14 on Sat, 09 Feb 2019 05:57:17 -0800