topcoder SRM 622 DIV2 BoxesDiv2

OpenSoucre發表於2014-06-04

注意題目這句話,Once you have each type of candies in a box, you want to pack those boxes into larger boxes, until only one box remains.

兩個box合併後必須放入更大一個盒子

題目的有點類似huffman的前部分,此題用堆去做,由於priority_queue是用堆實現的,故可以直接使用

每次從堆中選取最小的兩個進行合併即可

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

class BoxesDiv2{
public:
    int round_up(int x){
        for(int i = 0; i <=10 ; ++ i){
            if( 1<<i >= x ) return 1<<i;
        }
        return 1<<11;
    }
    
    int findSize(vector<int> candyCounts){
        priority_queue<int,vector<int>,greater<int> > boxQueue;
        for(int i = 0 ; i < candyCounts.size(); ++ i){
            boxQueue.push(round_up(candyCounts[i]));
        }
        while(boxQueue.size() != 1){
            int a = boxQueue.top();boxQueue.pop();
            int b = boxQueue.top();boxQueue.pop();
            boxQueue.push(max(a,b)*2);
        }
        return boxQueue.top();
    }
};

 

相關文章