POJ 1339(哈夫曼树)

poker card game

Time Limit: 1000MS
Memory Limit: 10000K

Description

Suppose you are given many poker cards. As you have already known, each card has points ranging from 1 to 13. Using these poker cards, you need to play a game on the cardboard in Figure 1. The game begins with a place called START. From START, you can walk to left or right to a rectangular box. Each box is labeled with an integer, which is the distance to START.
POJ 1339(哈夫曼树)_第1张图片
To place poker cards on these boxes, you must follow the rules below: (1) If you put a card with n points on a box labeled i , you got (n ∗ i) points. (2) Once you place a card on a box b, you block the paths to the boxes behind b. For example, in Figure 2, a player places a queen on the right box of distance 1, he gets 1 ∗ 12 points but the queen also blocks the paths to boxes behind it; i.e., it is not allowed to put cards on boxes behind it anymore.
POJ 1339(哈夫曼树)_第2张图片
Your goal: Given a number of poker cards, find a way to place them so that you will get the minimum points. For example, suppose you have 3 cards 5, 10, and K. To get the minimum points, you can place cards like Figure 3, where the total points are 1 * 13 + 2 * 5 + 2 * 10 = 43.
POJ 1339(哈夫曼树)_第3张图片

Input

The first line of the input file contains an integer n, n <= 10, which represents the number of test cases. In each test case, it begins with an integer m, m <= 100000,

which represents the number of poker cards. Next, each card represented by its number are listed consecutively. Note that, the numbers of ace, 2, 3, …, K are given by integers 1, 2, 3, …, 13, respectively. The final minimum point in each test case is less than 5000000.

Output

List the minimum points of each test case line by line.

Sample Input

3
3
5 10 13
4
3 4 5 5
5
7 7 10 11 13

Sample Output

43
34
110

思路:

题意:将n张扑克牌放到图1所示的空框中,得分为扑克牌点数乘以空框到树根的距离,求最小分数。

例:5,10,13,最小分数为:13 * 1 + 5 * 2 + 10 * 2 = 43

抽象:求哈夫曼树。

注意:输入用scanf,否则超时

AC代码:

#include 
#include 
#include 
#include 
using namespace std;
priority_queue<int,vector<int>,greater<int> >q;
int main()
{
    int t,n,num;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        while(q.empty()==false) q.pop();
        for(int i=0;iscanf("%d",&num);
            q.push(num);
        }
        int ans=0;
        while(q.size()>1)
        {
            int a=q.top();
            q.pop();
            int b=q.top();
            q.pop();
            ans+=a+b;
            q.push(a+b);
        }
        cout<return 0;
}

你可能感兴趣的:(数据结构,ACM)