HDU 5884 Sort (Huffman tree + two minutes)

Source: Internet
Author: User

In fact, this is Huffman tree, a start with priority queue write time-out, and later found that no priority queue, because each time the added value is always greater than before, then only need to use the normal queue can be, and this queue is monotonically increment, and then take the original array of the head or the head of the monotonous queue can be.

But without taking into account (n-1)% (k-1) ==0, the feeling that this condition is more difficult to think about, need to implement a preprocessing merge once.

Feeling can be derived by mathematical induction.

Main.cpp//Richard////Created by Shaojinjie on 16/9/22. COPYRIGHT©2016 year Shaojinjie.
All rights reserved. #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <
Queue> using namespace std;
typedef long Long LL;
const int maxn=200000+100;
int VAL[MAXN];
int n;
ll T;
    bool Merge (int k) {ll ans=0;
    int head=1,tail=n;
    Queue<ll> Q;
        if (k!=1&& (n-1)% (k-1)!=0) {for (int i=1;i<= (n-1)% (k-1) +1;i++) ans+=val[i];
        head= (n-1)% (k-1) +2;
    Q.push (ANS); } while (head<=tail| |!
        Q.empty ()) {int sum=0; for (int i=0;i<k;i++) {if (Head<=tail&&!q.empty () &&val[head]<q.front ()) {sum+=
            val[head++];}
            else if (!q.empty () &&head<=tail&&q.front () <=val[head]) {Sum+=q.front (); Q.pop ();}
            else if (Q.empty ()) {sum+=val[head++];} else if (head>tail) {sum+=q.front (); Q.Pop ();}
        } ans+=sum;
        if (ans>t) break;
        Q.push (sum);
    if (Q.size () ==1&&head>tail) break;
} return ans>t?false:true;
    } int main () {int t;
    scanf ("%d", &t);
        while (t--) {scanf ("%d%lld", &n,&t);
        for (int i=1;i<=n;i++) scanf ("%d", &val[i]);
        Sort (val+1,val+1+n);
        int k=0;
        int l=1,r=n;
            while (L<r) {k= (l+r)/2;
            if (merge (k)) r=k;
        else l=k+1;
    } printf ("%d\n", L);
} return 0; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.