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.
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).
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
Sample Output
9 10 12
2 2
给了n*n的数,每一行只能选一个数,然后n列选出n个数,他们的和记录下来,求最小的k个和(选的方式不同就算不一样的)
一开始想法就是优先队列,因为n的n次方肯定会炸,一定有的东西是要不搜的,就想到先对每行排序,然后最小的就可以出来,把每行后面的数与这行最小的数进行比较,然后根据差值入队,找次小,但是很快发现,这是没有一个标准比较的,意思就是根据入队不能将满足条件的数用队列表示出来。
然后看了lrj的想法- -,先是简化版的,只有两列数,那么就会有一个表(先对每一行排序)
a1 + b1 <= a1 + b2 <= a1 + b3 <= ……<=a1 + bn
a2 + b1 <= a2 + b2 <= a3 + b3<= ……<= a2 + bn
……
an + b1 <= an + b2 <= an + b3 <= …… <= an + bn
这样做的目的就是可以每次找出n个数,来代表所有的数,因为最小值一定在这n个数中产生。
这里还有一个存储技巧,就是用(s,b)来进行操作
(s,b)就是s = Aa +Bb;那么(s,b + 1) = (s,b) - Bb + B(b + 1);就可以了
现在这里是n行,就需要把这个想法推广。
假设我之前找了n个最小值,那么再来一行n个数,就算我只用了这里面的一个数,我也可以产生n个最小值,意思就是说,无论多么极限,更新之后的n个最小值一定是从这n个里面产生的。
数学归纳的思想。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<map>
#include<vector>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
int a[800],b[800];
int ans[800];
int leap[800];
struct Node
{
int y,num;
bool operator < (Node a)const
{
return num > a.num;
}
};
void work(int n)
{
priority_queue<Node>p;
Node temp;
Node now;
for(int i = 1;i <= n;i++)
{
temp.num = a[i] + b[1];
temp.y = 1;
p.push(temp);
}
for(int i = 1;i <= n;i++)
{
temp = p.top();p.pop();
a[i] = temp.num;
if(temp.y < n)
{
now.num = temp.num - b[temp.y] + b[temp.y + 1];
now.y = temp.y + 1;
p.push(now);
}
}
}
int main()
{
#ifdef LOCAL
freopen("C:\\Users\\ΡΡ\\Desktop\\in.txt", "r", stdin);
//freopen("C:\\Users\\ΡΡ\\Desktop\\out.txt","w",stdout);
#endif // LOCAL
int n;
while (scanf("%d", &n) != EOF)
{
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]);
sort(a + 1,a + 1 + n);
for(int i = 2;i <= n;i++)
{
for(int j = 1;j <= n;j++)scanf("%d",&b[j]);
sort(b + 1,b + 1 + n);
work(n);
}
for(int i = 1;i <= n;i++)
{
printf("%d",a[i]);
if(i < n)printf(" ");
else printf("\n");
}
}
return 0;
}