1. 程式人生 > 實用技巧 >Passing the Message HDU - 3410

Passing the Message HDU - 3410

原題連結

很明顯的單調棧,本題的要求是:每個人都要找到在他左邊,比他矮的人中最高的人的位置。且視野只限於到比他高的人為止

很容易分析出邊界點是比h[i]高的人,因此此單調棧內單調遞增,我們在pop的途中計算最高的即可

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 5e4+10;
 4 int h[N];
 5 int main()
 6 {
 7     freopen("in.txt","r",stdin);
 8     int t,kcase = 0;
 9     scanf("%d",&t);
10 while(t--){ 11 printf("Case %d:\n",++kcase); 12 stack<int> stk; 13 int n,L[N],R[N]; 14 scanf("%d",&n); 15 for(int i=1;i<=n;i++) scanf("%d",&h[i]); 16 for(int i=1;i<=n;i ++){ 17 int maxn = 0; 18 while(!stk.empty()&&h[stk.top()]<h[i]){
19 if(h[stk.top()]>maxn){ 20 maxn = h[stk.top()]; 21 L[i] = stk.top(); 22 } 23 stk.pop(); 24 } 25 if(maxn==0) L[i] = 0; 26 stk.push(i); 27 } 28 while(!stk.empty()) stk.pop();
29 for(int i=n;i>=1;i--){ 30 int maxn = 0; 31 while(!stk.empty()&&h[stk.top()]<h[i]){ 32 if(h[stk.top()]>maxn){ 33 maxn = h[stk.top()]; 34 R[i] = stk.top(); 35 } 36 stk.pop(); 37 } 38 if(maxn==0) R[i] = 0; 39 stk.push(i); 40 } 41 for(int i=1;i<=n;i++){ 42 printf("%d %d\n",L[i],R[i]); 43 } 44 } 45 return 0; 46 }

總結:

  1. 分析邊界點
  2. 分析單調遞增還是遞減棧
  3. 根據題目判斷是利用邊界點還是在利用while迴圈