POJ2442_Sequence_堆的应用

Sequence
Time Limit: 6000MS Memory Limit: 65536K
Total Submissions: 9314 Accepted: 3111

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

大致题意:

给出n*m的数,从每一行中取一个数构成一个数列,求所有元素相加之和最小的前n个数列。


大体思路:

实际上就是利用最大堆的性质。

1)输入第一行数,从小到大排序,保存在数组A中。

2)输入下一行数,从小到大排序,保存在数组B中。

3)取出数组B中的第一个元素,把它与数组A中所有的元素分别相加,和组成一个有n个元素最大堆。

4)取数组B中的下一个元素,从左往右与数组A中的元素相加。若和小于堆中的最大值,则删除堆中的最大值,把这个和插进去。若和大于堆中的最大值,则取数组B中的下一个元素重复本步骤。因为A和B都是从小到大排序的,若当前元素加数组A中靠前的元素都过大,后面的元素就不用试了。在本步骤中,最大堆始终保持着n个最小和。

5)B中元素全部取完后,将堆中的数字按从小到大的顺序保存在数组A中。然后返回步骤2)继续执行,直到除第一行以外的m-1行数操作完毕。

6)输出数组A即可。

因为我比较懒,所以直接用了stl里的优先对队列。。。


#include<cstdio>
#include<queue>
#include<algorithm>

int cas,m,n;
int A[2007],B[2007];
int main()
{
	//freopen("in.txt","r",stdin);

	scanf("%d",&cas);
	while(cas--){

		scanf("%d%d",&m,&n);

		for(int i=0;i<n;i++){
			scanf("%d",&A[i]);
		}
		std::sort(A,A+n);

		std::priority_queue<int>qu;

		for(int i=0;i<(m-1);i++){

			for(int j=0;j<n;j++)
				scanf("%d",&B[j]);
			std::sort(B,B+n);
			for(int j=0;j<n;j++)
				qu.push(A[j]+B[0]);
			for(int j=1;j<n;j++){
				int k;
				for(k=0;k<n;k++)
					if(A[k]+B[j]<qu.top()){
						qu.push(A[k]+B[j]);
						qu.pop();
					}
					else break;
			}
			for(int j=n-1;j>=0;j--){
				A[j]=qu.top();
				qu.pop();
			}

		}

		printf("%d",A[0]);
		for(int i=1;i<n;i++)
			printf(" %d",A[i]);
		printf("\n");

	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值