Topic Portal
Test Instructions: Training guide P189
Analysis: The idea of a complete reference book, K^k table into an orderly table:
Table 1:a1 + B1 <= A1 + B2 <= .... A1 + Bk
Table 2:a2 + B1 <= A2 + B2 <= ... A2 + Bk
.......
Table K:ak + B1 <= Ak + B2 <= ... Ak + Bk
can maintain a K-length array representing the current top-K small number and, when the array of line I is read, First push first, that is the smallest, then can be updated to the second, that is-b[i] + b[i+1]. The logn of the priority queue can be used to get the minimum value of each moment, and the total complexity becomes NLOGN
#include <bits/stdc++.h>using namespace Std;const int N = + 5;int a[n][n];int n;struct P{int V, id; P () {}p (int v, int id): V (v), ID (ID) {}bool operator < (const p&r) Const{return v > r.v;}}; void get_sum (int *a, int *b, int *c) {priority_queue<p> pque;for (int i=1; i<=n; ++i) {Pque.push (P (A[i] + b[1], 1 ));} for (int i=1; i<=n; ++i) {P r = pque.top ();p que.pop (); C[i] = r.v;int id = r.id;if (r.id < N) pque.push (P (R.v-b[id] + b[id+1], id+1));}} int main (void) {while (scanf ("%d", &n) = = 1) {for (Int. I=1; i<=n; ++i) {for (int j=1; j<=n; ++j) {scanf ("%d", & ; a[i][j]);} Sort (a[i]+1, a[i]+1+n);} for (int i=2; i<=n; ++i) {get_sum (a[1], a[i], a[1]);} for (int i=1; i<=n; ++i) {printf ("%d%c", a[1][i], i = = n? ' \ n ': ');}} return 0;}
Priority Queue UVA 11997 K smallest Sums