HDU Passing the Message Monotonic Stack

  • Passing the Message
  • The meaning
    of the question Given a set of numbers, find the position of the largest number in the left (and right) consecutively smaller numbers of each number.
  • Ideas
    Let’s first consider how to find the position of the largest number among the consecutively smaller numbers on its left side. This uses a simple data structure-monotonic stack.
    Monotonic stack: monotonic stack is actually a stack, but it uses some Clever logic makes the elements in the stack remain in order (monotonically increasing or monotonically decreasing) every time a new element is pushed onto the stack. Here we are going to use a monotonically decreasing stack (that is, the subscript from the bottom of the stack to the top of the stack is increasing) Yes, but the data is decreasing) By the way, the stack is monotonically increasing (the subscript is increasing from the bottom of the stack to the top of the stack, but the data is also increasing).
    In terms of principle, after reading the code, you can taste your product~
#pragma GCC optimize(2)
#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
#define pi acos(-1.0)
#define e exp(1.0)
#define pb push_back
#define mk make_pair
#define fir first
#define sec second
#define scf scanf
#define prf printf
typedef pair<ll,ll> pa;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int MAX_N=5e4+7;
int T,N;
int hei[MAX_N],resl[MAX_N],resr[MAX_N];
stack<int>S;
int main()
{
    
    
//  freopen(".../.txt","w",stdout);
//  freopen(".../.txt","r",stdin);
	ios::sync_with_stdio(false);
	cin>>T;
	int i,j,k=0;
	while(T--){
    
    
		cin>>N;
		for(i=1;i<=N;i++){
    
    
			cin>>hei[i];
		}
		while(!S.empty())
		S.pop();
		for(i=1;i<=N;i++){
    
    
			resl[i]=0;
			while(!S.empty()&&hei[S.top()]<hei[i]){
    
    
				resl[i]=S.top();
				S.pop();
			}
			S.push(i);
		}	
		while(!S.empty())
		S.pop();
		for(i=N;i;i--){
    
    
			resr[i]=0;
			while(!S.empty()&&hei[S.top()]<hei[i]){
    
    
				resr[i]=S.top();
				S.pop();
			}
			S.push(i);
		}	
		cout<<"Case "<<++k<<":"<<endl;
		for(i=1;i<=N;i++){
    
    
			cout<<resl[i]<<' '<<resr[i]<<endl;
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43311695/article/details/108739477