首页 > 技术文章 > poj 2442 Sequence(优先队列)

bfshm 2013-08-21 14:36 原文

题目:http://poj.org/problem?id=2442

题意:给你n*m的矩阵,然后每行取一个元素,组成一个包含n个元素的序列,一共有n^m种序列,

让你求出序列和最小的前n个序列的序列和。

          又是一个机智的题

 1 #include <iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<stack>
 6 #include<queue>
 7 #include<iomanip>
 8 #include<cmath>
 9 #include<map>
10 #include<vector>
11 #include<algorithm>
12 using namespace std;
13 
14 int a[20000],b[20000];
15 int main()
16 {
17 
18     priority_queue<int, vector<int>,less<int> >maxh;
19     int t,m,n,i,j;
20     cin>>t;
21     while(t--)
22     {
23         cin>>m>>n;
24         for(i=0; i<n; i++)
25         cin>>a[i];
26         sort(a,a+n); //
27         m--;
28         while(m--)
29         {
30             for(i=0; i<n; i++)
31             {
32                 cin>>b[i];
33                 maxh.push(a[0]+b[i]); //先让一个最小的与b加,做对比
34             }
35             sort(b,b+n); //排序
36             for(i=1; i<n; i++)
37             for(j=0; j<n; j++)
38             {
39                 if(a[i]+b[j]>maxh.top()) //如果第j个都大了,那后面的更大了
40                 break;
41                 maxh.pop();
42                 maxh.push(a[i]+b[j]);
43             }
44             for(i=n-1; i>=0; i--)
45             {
46                 a[i]=maxh.top(); //a数组是前k列里的组合的最小值
47                 maxh.pop();
48             }
49         }
50         for(i=0; i<n-1; i++)
51         printf("%d ",a[i]);  
52         if(n>=1)
53         printf("%d\n",a[i]);
54     }
55     return 0;
56 }

 

推荐阅读