2269: minval (priority queue heap sort)

2269: minval

Time Limit: 3 Sec Memory Limit: 256 MB
Commits: 638 Resolved: 65
[ Commit ][ Status ][ Discussion Board ][Proposer:ExternalImport]

Topic description

There are two sequences A and B of length N. If you add any number in A and B, you can get N 2 sums , and find the smallest N among the N 2 sums .

enter

Enter a positive integer N (1<=N<=100000) in the first line;

The second row contains N integers Ai and Ai<=10 9 ; the third row contains N integers Bi and Bi<=10 9 .

output

The output is only one line, containing n integers, the n smallest sums are output from small to large, and adjacent numbers are separated by spaces.

sample input

5
1 3 2 4 5
6 3 4 1 7

Sample output

2 3 4 4 5
/* heap sort (priority queue)
* maintain the n smallest numbers
* Don't forget to sort
*/

#include<queue>
#include<iostream>
#include<cstdio>
#include<algorithm>

using namespace std ; 


#define maxn 110000
int n ; 
int num1[maxn] , num2[maxn] ; 

priority_queue<int> min_num ; 
int result[maxn] ; 

int main(){
    cin>>n ; 

    for(int i=1 ; i<=n ; i++){
        scanf("%d" , &num1[i]) ; 
    }
    for(int j=1 ; j<=n ; j++){
        scanf("%d" , &num2[j]) ; 
    }
    sort(num1+1 , num1+n+1) ; 
    sort(num2+1 , num2+1+n) ; 

    for(int i=1 ; i<=n ; i++){
        min_num.push(num1[1] + num2[i]) ; 
    }
    for(int i=2 ; i<=n ; i++){
        for(int j=1 ; j<=n ; j++){
            if(num1[i] + num2[j] < min_num.top()){
                min_num.pop() ;
                min_num.push(num1[i] + num2[j]) ; 
            }else {
                break ; 
            }
        }
    }

    for(int i=1 ; i<=n ; i++){
        result[i] = min_num.top() ; 
        min_num.pop() ;
    }

    for(int i=n ; i>=1 ; i--){
        printf("%d " , result[i]) ; 
    }


    return 0 ; 
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326281280&siteId=291194637