poj2442 Sequence(堆)

Sequence

Description
Given m sequences, each contains n non-negative integer. Now we may select one number from each sequence to form a sequence with m integers. It’s clear that we may get n ^ m this kind of sequences. Then we can calculate the sum of numbers in each sequence, and get n ^ m values. What we need is the smallest n sums. Could you help us?

Input
The first line is an integer T, which shows the number of test cases, and then T test cases follow. The first line of each case contains two integers m, n (0 < m <= 100, 0 < n <= 2000). The following m lines indicate the m sequence respectively. No integer in the sequence is greater than 10000.

Output
For each test case, print a line with the smallest n sums in increasing order, which is separated by a space.

Sample Input
1
2 3
1 2 3
2 2 3

Sample Output
3 3 4

题意:M个序列,每个序列N个数,从每个序列中取一个数求和,求其中最小的N个和。

分析:维护一个大小为N的大根堆,把每一行的数与堆中的数相加,如果小于堆顶就替换掉堆顶,最后堆中的N个数就是答案。

代码

#include <cstdio>
#include <algorithm>
#include <queue>
#define N 2005
using namespace std;

priority_queue<int> q;
int a[N],n,m,T;

int main()
{
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d%d", &m, &n);
        for (int i = 1; i <= n; i++)
        {
            int x;
            scanf("%d", &a[i]);
            q.push(a[i]);
        }
        for (int i = 1; i < m; i++)
        {
            for (int j = 1; j <= n; j++)
                a[j] = q.top(),q.pop();
            for (int j = 1; j <= n; j++)
            {
                int x;
                scanf("%d", &x);
                for (int k = 1; k <= n; k++)
                    if (q.size() >= n)
                    {
                        if (q.top() > a[k] + x)
                            q.pop(),q.push(a[k] + x);
                    }
                    else q.push(a[k] + x);
            }
        }
        for (int i = 1; i <= n; i++)
            a[i] = q.top(),q.pop();
        for (int i = n; i >= 1; i--)
            printf("%d ", a[i]);
        printf("\n");
    }
}

猜你喜欢

转载自blog.csdn.net/zhanghaoxian1/article/details/81774167