Luogu: P1631 sequence merger (popularity +/improvement, binary heap and ST table)

topic:

Analysis: It seems simple, but quite complicated.

Violence+vector:

Insert picture description here

#include<bits/stdc++.h>
using namespace std;
int m;
int main()
{
    
    
 //priority_queue<int,vector<int>,greater<int> > q;
 cin>>m;
 int A[m];
 vector<int> v;
 for(int i=0;i<m;i++) cin>>A[i];
 int c;
 for(int i=0;i<m;i++)
 {
    
    
  cin>>c;
  for(int ii=0;ii<m;ii++) v.push_back(c+A[ii]);
 }
 sort(v.begin(),v.end());
 for(int i=0;i<m;i++) cout<<v[i]<<' ';
}

Violence+queue:

Insert picture description here

#include<bits/stdc++.h>
using namespace std;
int m;
int main()
{
    
    
 priority_queue<int,vector<int>,greater<int> > q;
 cin>>m;
 int A[m];
 vector<int> v;
 for(int i=0;i<m;i++) cin>>A[i];
 int c;
 for(int i=0;i<m;i++)
 {
    
    
  cin>>c;
  for(int ii=0;ii<m;ii++) q.push(c+A[ii]);
 }
 for(int i=0;i<m;i++)
 {
    
    
  cout<<q.top()<<' ';
  q.pop();
  } 
}

I should be able to think of it.

It turns out that this is the application of the heap:

Insert picture description here

Code:

#include<bits/stdc++.h>
using namespace std;
int m;
struct node{
    
    
 int x;
 int y;
 bool operator < (const node & nn) const
 {
    
    
  return y>nn.y;
 }
};
int main()
{
    
    
 cin>>m;
 int A[m];
 int B[m];
 priority_queue<node> q;
 for(int i=0;i<m;i++) cin>>A[i];
 for(int i=0;i<m;i++) cin>>B[i];
 for(int i=0;i<m;i++)
 {
    
    
  struct node nn;
  nn.x=0;
  nn.y=A[0]+B[i]; 
  q.push(nn);
 }
 for(int i=0;i<m;i++)
 {
    
    
  struct node nn=q.top();
  q.pop();
  cout<<nn.y<<' ';
  nn.y=nn.y-A[nn.x]+A[nn.x+1];
  nn.x++; 
  q.push(nn);
 }
}

Guess you like

Origin blog.csdn.net/weixin_42721412/article/details/108562959
Recommended