POJ 2442 Sequence【堆】

來源:互聯網
上載者:User

題目連結:http://poj.org/problem?id=2442

題目大意:給出一個m*n的矩陣,從每一行中取出一個數相加,能得到n^m個不同的結果,要求輸出其中前n項。

建立一個以n元數組為底層數組的堆,在這裡,利用stl中的make_heap,pop_heap,push_heap等函數解決。

1.將第一組資料輸入arr1數組,升序排序。

2.將接下來的資料輸入到arr2數組中,並且heap[i]=arr1[0]+arr2[0...n-1],make_heap(heap,heap+n).

3.arr1數組從1到n-1,比較temp=arr1[i]+arr2[0...n-1]與堆頂的元素,如果temp比較小,則將堆頂元素pop,添加temp到heap;否則跳出迴圈。

4.將heap中的元素全部賦值給arr1數組,升序排序,重複2,3兩步,直到所有資料全部處理完。

代碼:

#include <iostream>#include <cstdio>#include <algorithm>#define M 111#define N 2111using namespace std;int arr1[N],arr2[N],heap[N];int m,n;int main(){    int t;    bool s=true;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&m,&n);        for(int i=0;i<n;i++)            scanf("%d",&arr1[i]);        sort(arr1,arr1+n);        for(int i=1;i<m;i++)        {            for(int j=0;j<n;j++)                scanf("%d",&arr2[j]);            sort(arr2,arr2+n);            for(int j=0;j<n;j++)                heap[j]=arr1[0]+arr2[j];            make_heap(heap,heap+n);            for(int j=1;j<n;j++)            {                for(int k=0;k<n;k++)                {                    int temp=arr1[j]+arr2[k];                    if(temp<heap[0])                    {                        pop_heap(heap,heap+n);//將heap裡的最大值放在最後,並且重新修正heap                        heap[n-1]=temp;                        push_heap(heap,heap+n);                        s=false;                    }                    else                        break;                }                if(s)                    break;            }            for(int j=0;j<n;j++)                arr1[j]=heap[j];            sort(arr1,arr1+n);        }        for(int i=0;i<n;i++)            printf("%d ",arr1[i]);        printf("\n");    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.