Describe
You’re given k arrays, each array has k integers. There are k^k 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.
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).
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
Sample Output
9 10 12
2 2
题意:输入一个k,然后输入k行k列个数,从每一行中选取一个数,使得他们之和最小,并从所有(k^k个数)中排列出k个最小的数——从小到大。
对于这样的题,我联想到了刚学习过的矩阵(同出一辙吧):
输入的数为a11, a12, a13,......, a1k
a21, a22, a23,......, a2k
.......
ak1, ak2, ak3,......, akk
不妨先看一二两排,我们可以寻找一二两排的和最小k个数。
证明如下:
我们先假设只有两排,分别为{排a ,排b }。
则有:
a1+b1 <= a2+b1 <= a3+b1 <=......<= ak+b1
a1+b1 <= a1+b2 <= a1+b3 <=......<= a1+bk
类似的我们可以得到这样一张表(默认在表中元素左边和上方的数小于等于该元素):
a1+b1 a1+b2 ...... a1+bk
a2+b1 a2+b2 ...... a2+bk
...... ......
ak+b1 ak+b2 ...... ak+bk
现在我们只需要从这表中找到n个最小的数再次赋给a,然后在和下一组的b重复上面的运算就可以慢慢的得到最后一组我们要的k个数的答案。
思路:
根据上面的证明,现在需要的就是对于处理每一个和对象,不难想到,这里需要用到优先队列,然后从a1+b1(这个注定是最小值)开始,我们查看a2+b1与a1+b2往下谁的值会是下一个小的数。
主要函数:
void work()
{
priority_queue<node> Q;
node temp;
node now;
for(int i=1; i<=k; i++)
{
temp.s=A[i]+B[1];
temp.b=1;
Q.push(temp);
}
for(int i=1; i<=k; i++)
{
temp=Q.top();
Q.pop();
A[i]=temp.s;
if(temp.b<k)
{
now.s=temp.s-B[temp.b]+B[temp.b+1];
now.b=temp.b+1;
Q.push(now);
}
}
}
这里,我们处理的B数组是有序的。
然后,很多人可能不懂我的if判断下的功能是什么,讲解一下:我们知道第一个判断的数是a1+b1,但显然如果没有这一串if语句,我们的下一个数只能是a2+b1,调用if语句的目的就是使得B数组也可以往后找。
AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
int k;
int A[800],B[800];
struct node
{
int s,b;
node()
{}
node(int _s, int _b)
{
s=_s;
b=_b;
}
friend bool operator<(node a, node c)
{
return a.s>c.s;
}
};
void work()
{
priority_queue<node> Q;
node temp;
node now;
for(int i=1; i<=k; i++)
{
temp.s=A[i]+B[1];
temp.b=1;
Q.push(temp);
}
for(int i=1; i<=k; i++)
{
temp=Q.top();
Q.pop();
A[i]=temp.s;
if(temp.b<k)
{
now.s=temp.s-B[temp.b]+B[temp.b+1];
now.b=temp.b+1;
Q.push(now);
}
}
}
int main()
{
while(scanf("%d",&k)!=EOF)
{
for(int i=1; i<=k; i++)
{
scanf("%d",&A[i]);
}
for(int i=2; i<=k; i++)
{
for(int j=1; j<=k; j++)
{
scanf("%d",&B[j]);
}
sort(B+1, B+k+1);
work();
}
for(int i=1; i<=k; i++)
{
printf("%d",A[i]);
if(i<k) printf(" ");
else printf("\n");
}
}
return 0;
}