Original question:
You ' re given k-arrays, each with a k integers. There is k-K ways to pick exactly one element with each array and calculate the sum of the integers. Your task is to find the K smallest sums among them.
Input
There'll be several test cases. The first line of each case is contains an integer k (2≤k≤750). Each of the following K lines contains k positive integers in each array. Each of the 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
English:
Give you the K number, each array has a number of K. Now ask you each array to take a number plus sum together, then the smallest of the first k is how much.
#include <bits/stdc++.h> using namespace std;
int k;
Vector<int> V[751],ans;
struct item {int s,b;
Item (int s,int b): s (s), B (b) {} BOOL operator < (const item &RHS) Const {return s>rhs.s;
}
};
void Ini () {for (int i=1;i<=k;i++) v[i].clear ();}
void Merge (vector<int> tmp) {priority_queue<item> PQ;
for (int i=0;i<ans.size (); i++) Pq.push (item (ans[i]+tmp[0],0));
for (int i=0;i<k;i++) {item t=pq.top ();
Pq.pop ();
Ans[i]=t.s;
int b=t.b;
if (b+1<k) Pq.push (item (t.s-tmp[b]+tmp[b+1],b+1));
}} int main () {Ios::sync_with_stdio (false);
while (cin>>k) {ini ();
for (int i=1;i<=k;i++) {for (int j=1;j<=k;j++) {int res;
cin>>res;
V[i].push_back (RES);
} sort (V[i].begin (), V[i].end ());} Ans=v[1];
for (int i=2;i<=k;i++) Merge (V[i]);
for (int i=0;i<ans.size (); i++) if (I!=ans.size ()-1) cout<<ans[i]<< "";
else cout<<ans[i]<<endl;
} return 0;
}
idea:
The example in the training guide thought for a while without thinking and looking directly at the answer. The idea is ingenious. The
assumes that there are two arrays before K and Min are saved in ans, and now there is a third array, then the minimum value of the three array is the first k value of the current save plus the K values in the third array. The
maintains the first k minimum values with a priority queue, and then uses the recursive idea to calculate the number of the first and second values in the third array at a time.