【题目链接】
http://poj.org/problem?id=2442
【算法】
堆
【代码】
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXM 110 #define MAXN 2010 int T,n,m,i,j; int a[MAXM][MAXN],ans[MAXN]; struct info { int p,q,val; bool last; friend bool operator < (info a,info b) { return a.val > b.val; } } ; inline void _merge(int *a,int *b) { int i,j; priority_queue< info > q; static int res[MAXN]; info tmp; while (!q.empty()) q.pop(); q.push((info){1,1,a[1]+b[1],false}); for (i = 1; i <= n; i++) { tmp = q.top(); q.pop(); res[i] = tmp.val; q.push((info){tmp.p,tmp.q+1,a[tmp.p]+b[tmp.q+1],true}); if (!tmp.last) q.push((info){tmp.p+1,tmp.q,a[tmp.p+1]+b[tmp.q],false}); } for (i = 1; i <= n; i++) a[i] = res[i]; } int main() { scanf("%d",&T); while (T--) { scanf("%d%d",&m,&n); for (i = 1; i <= m; i++) { for (j = 1; j <= n; j++) scanf("%d",&a[i][j]); sort(a[i]+1,a[i]+n+1); } for (i = 1; i <= n; i++) ans[i] = a[1][i]; for (i = 2; i <= m; i++) _merge(ans,a[i]); for (i = 1; i < n; i++) printf("%d ",ans[i]); printf("%d\n",ans[n]); } return 0; }