有序表合并。给出n * n的数组,要求每行取一个,输出总和前n小的。题目理解不难,但不是很好想。白书上讲的很清楚。
首先,每行最小的数加在一起,一定是第一个输出的数,没有比他更小的了。
先把第一行由小到大排序记为Ai,然后考虑下一行Bi。把所有的Ai+Bj都加起来,排序后,只要取前n个就够了,后边的一定不会比之前的更优。但这样做会超时,所以不能都算一遍。先把B0跟所有的Ai相加,放入优先队列中,每次取队首(为最小值,设为Bx),然后下一个最小值可能在队里,也可能是由Ai与Bx+1组成的,所以把Ai-Bx+Bx+1放入队里中。话句话说,假如A0+B0最小,那么下一个是A1+B0,还是A0+B1呢?而A1+B0在队列里,Ai-Bx+Bx+1表示的就是A0+B0->A0+B1。
一直这样累加,最后的Ai就是要求结果。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<string>
#include<queue>
#include<cmath>
///LOOP
#define REP(i, n) for(int i = 0; i < n; i++)
#define FF(i, a, b) for(int i = a; i < b; i++)
#define FFF(i, a, b) for(int i = a; i <= b; i++)
#define FD(i, a, b) for(int i = a - 1; i >= b; i--)
#define FDD(i, a, b) for(int i = a; i >= b; i--)
///INPUT
#define RI(n) scanf("%d", &n)
#define RII(n, m) scanf("%d%d", &n, &m)
#define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k)
#define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p)
#define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q)
#define RFI(n) scanf("%lf", &n)
#define RFII(n, m) scanf("%lf%lf", &n, &m)
#define RFIII(n, m, k) scanf("%lf%lf%lf", &n, &m, &k)
#define RFIV(n, m, k, p) scanf("%lf%lf%lf%lf", &n, &m, &k, &p)
#define RS(s) scanf("%s", s)
///OUTPUT
#define PN printf("\n")
#define PI(n) printf("%d\n", n)
#define PIS(n) printf("%d ", n)
#define PS(s) printf("%s\n", s)
#define PSS(s) printf("%s ", n)
///OTHER
#define pb(x) push_back(x)
#define CLR(a, b) memset(a, b, sizeof(a))
#define CPY(a, b) memcpy(a, b, sizeof(b))
#define display(A, n, m) {REP(i, n){REP(j, m)PIS(A[i][j]);PN;}}
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int MOD = 100000000;
const int INFI = 1e9 * 2;
const LL LINFI = 1e17;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int N = 777;
const int M = 11;
const int move[8][2] = {0, 1, 0, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1};
struct node
{
int s, num;
node(){};
node(int a, int b){s = a, num = b;};
bool operator < (const node a) const
{
return a.s < s;
}
}p;
int a[N], b[N], n;
void add()
{
priority_queue<node> q;
REP(i, n)q.push(node(a[i] + b[0], 0));
REP(i, n)
{
p = q.top();
q.pop();
a[i] = p.s;
q.push(node(a[i] - b[p.num] + b[p.num + 1], p.num + 1));
}
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
while(RI(n) != EOF)
{
REP(i, n)RI(a[i]);
sort(a, a + n);
REP(i, n - 1)
{
REP(j, n)RI(b[j]);
sort(b, b + n);
add();
}
printf("%d", a[0]);
FF(i, 1, n)printf(" %d", a[i]);
PN;
}
return 0;
}