Problem:POJ2442 - Sequence

  1. Problem:POJ2442 - Sequence
  2. Begin Time : 2nd/March/2012 1:00 p.m.
  3. End Time: 2nd/March/2012 4:14 p.m
  4. Cost Time: 3H 14Min
  5. 看的别人的解题报告过的,非常感谢
  6. http://hi.baidu.com/%C0%B6%C9%ABarch/blog/item/f9d343f49cd92e53d7887d73.html
  7. 的博主!
  8. 思路:
  9. 我们要找到n个smallest的数,用贪心法可以解决这一问题。
  10. (1)维护两个数组,a和b,以及一个大根堆p
  11. 循环不变式:
  12. (1)初始化
  13. 将元素读入a,将a排序(从小到大)
  14. 执行并重复(2)
  15. (2)保持
  16. 对于这全部数据第二行到第m行(从第二行开始,因为第一行读到a里了)
  17. 将元素读入b,将b排序(从小到大)
  18. For i = 0 to n -1
  19. heap.push(a[i]+b[0]);
  20. 然后
  21. for(int i = 1; i < n;i++)
  22. {
  23. for(int j = 0 ; j < n; j++)
  24. {
  25. if( (b[i] + a[j]) > heap.top() ) break;
  26. heap.pop(); ///从heap中删除一个最大的元素,从而保证heap中元素数目不变
  27. heap.push(b[i] + a[j]);
  28. }
  29. }
  30. /////这样,就选出了n个最小值
  31. 然后把heap中的n个值按照从小到大给
  32. a[1] -> a[n],并将heap清空。
  33. 执行(2)
  34. (3)最终结果
  35. 输出a中全部元素就可以了,注意,对于每个case都要换行哦!

 

#include "stdafx.h"
#include <cstdio>  
#include <cstring>  
#include <cstdlib>  
#include <iostream>  
#include <vector>  
#include <queue>
#include<conio.h>
#include <algorithm>  
//#define INPUT  
using namespace std; 
bool comp(int a,int b) 

    return b > a; 

int main ()
{
vector <int>a;
vector<int>b;
int x;
cin>>x;
while (x--)
{
 int m,n;
   a.clear();
   b.clear(); 
 cin>>m>>n;
 for(int i=0;i<n;i++)
 {
  int buf;
  cin>>buf;
  a.push_back (buf);   
 }
  sort(a.begin(),a.end(),comp); 
    priority_queue <int> q;
 for(int j=0;j<m-1;j++)
 {
        for(int i=0;i<n;i++)
  {
    int buf;
    cin>>buf;
    b.push_back (buf); 
  }
   sort(&b[0],&b[0]+n,comp); 
          for(int z=0;z<n;z++)
    {
             q.push (a[z]+b[0]);
    }
           for(int i=1;i<n;i++)
     {
      for(int z=0;z<n;z++)
      {
       if(q.top()>a[z]+b[i])
       {
                     q.pop();
      q.push(a[z]+b[i]);
       }
       else break;
      }
     }
     for(int z=0;z<n;z++)
     {
      a[n-z-1]=q.top();
      q.pop();

     }
 }
    for( int z=0;z<n-1;z++)
     {
     cout<<a[z]<<" ";

     }
cout<<a[n-1];
 cout<<endl;
 getch();
 
}
 return 0;
}

posted @ 2012-10-17 20:46  MFT  阅读(549)  评论(0编辑  收藏  举报