【暑假】[实用数据结构]UVa11997 K Smallest Sums
2015-08-07 12:08
701 查看
UVa11997 K Smallest Sums
题目:
思路:
先思考2个有序表(sort后)AB合成的情况。组织如下
【 表】1: A1+B1 <= A1+B2 <= A1+B3 <=......
【表】2:A2+B1 <= A2+B2 <= A2+B3 <=......
......
【表】n:An+B1 <= An+B2 <= An+B3 <=......
转化为多路归并问题且有总数限制为k,因此将n个【表】合并为一个有序【表】C且表中数据数目为k。优先队列处理:初始化优先队列为n个表的第一元素,每次在队列中取出最小元素加入C并将该最小元素在【表】中的后一个元素入队。共取k个元素。
对于k个有序表的情况:两两合并。
于是有代码如下:
题目:
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 ------------------------------------------------------------------------------------------------------------------------------------------------------------------
思路:
先思考2个有序表(sort后)AB合成的情况。组织如下
【 表】1: A1+B1 <= A1+B2 <= A1+B3 <=......
【表】2:A2+B1 <= A2+B2 <= A2+B3 <=......
......
【表】n:An+B1 <= An+B2 <= An+B3 <=......
转化为多路归并问题且有总数限制为k,因此将n个【表】合并为一个有序【表】C且表中数据数目为k。优先队列处理:初始化优先队列为n个表的第一元素,每次在队列中取出最小元素加入C并将该最小元素在【表】中的后一个元素入队。共取k个元素。
对于k个有序表的情况:两两合并。
于是有代码如下:
#include<cstdio> #include<algorithm> #include<queue> #define FOR(a,b,c) for(int a=(b);a<(c);a++) using namespace std; const int maxn = 800 + 10; struct Node{ int s,b; bool operator <(const Node& rhs) const{ //相反定义 < return s>rhs.s; } }; void merge(int* A,int* B,int*C,int n){ //合并AB数组取其前n小的和放入C priority_queue<Node> Q; FOR(i,0,n) Q.push(Node{A[i]+B[0],0}); FOR(i,0,n){ Node u=Q.top();Q.pop(); C[i]=u.s; int b=u.b; if(b+1 < n) Q.push(Node{u.s-B[b]+B[b+1],b+1}); //加入A[a][b+1] } } int main(){ int n; int A[maxn],B[maxn]; while(scanf("%d",&n)==1){ FOR(j,0,n) scanf("%d",&A[j]); sort(A,A+n); FOR(i,1,n){ FOR(j,0,n) scanf("%d",&B[j]); sort(B,B+n); merge(A,B,A,n); } printf("%d",A[0]); FOR(i,1,n) printf(" %d",A[i]); printf("\n"); } return 0; }
相关文章推荐
- 数据结构和算法绪论
- 【暑假】[实用数据结构]UVAlive 3135 Argus
- 【暑假】[实用数据结构]UVa11991 Easy Problem from Rujia Liu?
- 【暑假】[实用数据结构]UVa11995 I Can Guess the Data Structure!
- 数据结构之树和二叉树---二叉树的遍历
- 数据结构之树状数组
- 数据结构之树和二叉树---二叉树的基本操作
- 数据结构实验:连通分量个数
- 数据结构实验:连通分量个数
- 编程中最没用的东西是源代码,最有用的东西是算法和数据结构(转载)
- hdu1016 数据结构之面向过程的深搜算法
- 01-复杂度1. 最大子列和问题(20)
- 实验数据结构(保存了两日内书面实验报告) 列表中的整合
- 浅谈算法和数据结构: 一 栈和队列
- 浅谈算法和数据结构: 二 基本排序算法
- 浅谈算法和数据结构: 三 合并排序
- 浅谈算法和数据结构: 四 快速排序
- 浅谈算法和数据结构: 五 优先级队列与堆排序
- 浅谈算法和数据结构: 六 符号表及其基本实现
- 浅谈算法和数据结构: 七 二叉查找树