• poj2442优先队列


    1. 感谢
    2. http://hi.baidu.com/%C0%B6%C9%ABarch/blog/item/f9d343f49cd92e53d7887d73.html
    3. 的博主!
    4. 思路:
    5. 我们要找到n个smallest的数,用贪心法可以解决这一问题。
    6. (1)维护两个数组,a和b,以及一个大根堆p
    7. 循环不变式:
    8. (1)初始化
    9. 将元素读入a,将a排序(从小到大)
    10. 执行并重复(2)
    11. (2)保持
    12. 对于这全部数据第二行到第m行(从第二行开始,因为第一行读到a里了)
    13. 将元素读入b,将b排序(从小到大)
    14. For i = 0 to n -1
    15. heap.push(a[i]+b[0]);
    16. 然后
    17. for(int i = 1; i < n;i++)
    18. {
    19. for(int j = 0 ; j < n; j++)
    20. {
    21. if( (b[i] + a[j]) > heap.top() ) break;
    22. heap.pop(); ///从heap中删除一个最大的元素,从而保证heap中元素数目不变
    23. heap.push(b[i] + a[j]);
    24. }
    25. }
    26. /////这样,就选出了n个最小值
    27. 然后把heap中的n个值按照从小到大给
    28. a[1] -> a[n],并将heap清空。
    29. 执行(2)
    30. (3)最终结果
    31. 输出a中全部元素就可以了,注意,对于每个case都要换行哦!
    32. #include <iostream>
      #include <stdio.h>
      #include <queue>
      #include <math.h>
      #include <string>
      #include <algorithm>
      using namespace std;
      bool cmp(int a,int b)
      {
          return a<b;
      }
      int main()
      {
          int a[2010],b[2010];
          int n,m,i,j,t,y;
          cin>>t;
          while(t--)
          {
              scanf("%d%d",&m,&n);
              for(i=0;i<n;i++)
                  scanf("%d",&a[i]);
              sort(a,a+n,cmp);
              priority_queue <int> q;
              for(i=1;i<m;i++)
              {
                  for(j=0;j<n;j++)
                    scanf("%d",&b[j]);
                  sort(b,b+n,cmp);
                  for(j=0;j<n;j++)
                  {
                      q.push(b[0]+a[j]);
                  }
                  for(j=1;j<n;j++)
                  {
                      for(y=0;y<n;y++)
                      {
                          if(a[y]+b[j]>=q.top()) break;
                          q.pop();
                          q.push(a[y]+b[j]);
                      }
                  }
                  for(j=0;j<n;j++)
                  {
                      a[n-1-j]=q.top();
                      q.pop();
                  }
              }
              for(i=0;i<n;i++)
              {
                  if(i==0)
                      printf("%d",a[i]);
                  else
                      printf(" %d",a[i]);
              }
              cout << endl;
          }
          return 0;
      }
  • 相关阅读:
    CXX解析CSV文件
    linux通过cifs挂载windows共享目录
    oracle生产环境存储过程调试方案
    imp导入库表空间找不到问题记录
    银行怎么盘头寸
    jQuery插件之【jqGrid】常用语法整理-【更新】
    Jquery一些笔记
    request对象的五个集合
    jQuery插件之【jqGrid】常用语法整理-【更新】
    MVC中几种常用ActionResult
  • 原文地址:https://www.cnblogs.com/yuanbo123/p/6368613.html
Copyright © 2020-2023  润新知