K Smallest Sums

You're given k arrays, each array has k integers. There are kk ways to pick exactly one element in each array and calculate the sum of the integers. Your task is to find the k smallest sums among them.

Input

There will be several test cases. The first line of each case contains an integer k (2<=k<=750). Each of the following k lines contains k positive integers in each array. Each of these integers does not exceed 1,000,000. The input is terminated by end-of-file (EOF). The size of input file does not exceed 5MB.

Output

For each test case, print the k smallest sums, in ascending order.

Sample Input

3
1 8 5
9 2 5
10 7 6
2
1 1
1 2

Output for the Sample Input

9 10 12
2 2 题目大意:给k个数组各含k个整数,求每个数组中取一个元素他们的和最小的前k个。
分析:一共有k的k次方个和,先看只有两个数组的情况(从小到大排好序的)
1 2 3 ...
1 A1+B1<=A1+B2<=A1+B3.....
2 A2+B1<=A2+B2<=A2+B3.....
...........................
若计算两两之和需k的平方次不可取(时间复杂度O(n的平方))
用优先队列找出最小的前k个和(时间复杂度O(nlogn))
由上面的表格知,第一行的k个元素在它所在列中是和最小的,但不是最小的前k个
把第一行的元素放入优先队列中,把队列的顶部元素提取出来,它是队列中最小的(A[a]+B[b])
也是两两之和中未被提取出来的最小的,把与它最相近的即比它大或等于它的(A[a]+B[b+1])
元素放入队列中。
以此类推提取出来的k个元素是最小的前k个。
两两数组合并从而求得最后结果。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std; const int Max=;
int A[Max][Max]; struct Item
{
int s,b;
Item() {}
Item(int s,int b):s(s),b(b) {}
bool operator < (const Item &a)const{
return a.s<s;
}
}item; void merge(int *A,int *B,int *C,int n)
{
priority_queue<Item> pq;
int i,b;
for(i=;i<n;i++) pq.push(Item(A[i]+B[],));
for(i=;i<n;i++)
{
item=pq.top();pq.pop();
C[i]=item.s;b=item.b;
if(b+<n) pq.push(Item(C[i]-B[b]+B[b+],b+));
}
}
int main()
{
int n,i,j;
while(~scanf("%d",&n))
{
for(i=;i<n;i++)
{
for(j=;j<n;j++) scanf("%d",&A[i][j]);
sort(A[i],A[i]+n);
}
for(i=;i<n;i++)
merge(A[],A[i],A[],n);
for(i=;i<n;i++) printf(i?" %d":"%d",A[][i]);
printf("\n");
}
return ;
}

 

最新文章

  1. c#和js互通的AES加密解密
  2. 【转】Js获取当前日期时间及格式化操作
  3. [界面开发新秀]免费的AYUI,开发360领航版系列教程[2/40]
  4. Android如何使用so文件和Android studio中导入so
  5. 转:对TCP/IP网络协议的深入浅出归纳
  6. Qt:使用自定义的字体
  7. How to use draggable attribute?怎样使用拖拽属性代码分享
  8. office-excel
  9. java-递归练习
  10. Linux系统下为何病毒少?原因竟是这个?
  11. Neo4j导入本地csv问题
  12. 数据库返回刚插入记录的ID
  13. Python3编写网络爬虫02-基本请求库requests的使用
  14. analytics详解
  15. Mysql 根据时间统计总数
  16. 蓝凌OA常用表整理
  17. 如何在Linux环境下通过uwgsi部署Python服务
  18. 792. Number of Matching Subsequences
  19. 20155216 2016-2017-2 《Java程序设计》第七周学习总结
  20. linux入门总结

热门文章

  1. spring 常用问题汇总
  2. Invalid bound statement (not found): com.ros.dao.LogMapper.insert
  3. 博客-从github ghpage 转回通知
  4. django 第一次运行出错
  5. Spring框架xml配置文件 复杂类型属性注入——数组 list map properties DI dependency injection 依赖注入——属性值的注入依赖于建立的对象(堆空间)
  6. Broadcast BCM94322 用ubuntu修改ID
  7. mac拷贝原版和权限修复的命令行工具
  8. 使用iptables缓解DDOS及CC攻击
  9. MySQL中日期函数的使用
  10. Spring容器的理解