1、京东OJ 保卫方案 (单调栈)
http://www.cnblogs.com/mengmz/p/7263915.html
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct node{ int val; long count; node(int v, int c = 1): val(v), count(c){} }; int main() { int N; while(cin >> N){ vector<int> watch(N); for(int i = 0; i < N; ++i) cin >> watch[i]; vector<node> v; node tmp(watch[0]); int max_h = watch[0]; int max_index = 0; for(int i = 1; i < N; ++i){ if(watch[i] == watch[i - 1]) tmp.count ++; else{ v.push_back(tmp); if( max_h < tmp.val){ max_h = tmp.val; max_index = v.size() - 1; } tmp.val = watch[i]; tmp.count = 1; } } // 最后一个元素 v.push_back(tmp); if( max_h < tmp.val){ max_h = tmp.val; max_index = v.size() - 1; } int n = 0; long count = 0; vector<node> stack; for(int i = max_index; n < v.size(); ++n, i = (i+1)%v.size()){ while( stack.size() && v[i].val > stack[stack.size() - 1].val){ node & tmp = stack[stack.size() - 1]; count += 2 * tmp.count + tmp.count*(tmp.count - 1)/2; stack.pop_back(); } if( stack.size()){ if(v[i].val == stack[stack.size() - 1].val) stack[stack.size() - 1].count += v[i].count; else stack.push_back(v[i]); } else stack.push_back(v[i]); } while(stack.size()){ node & tmp = stack[stack.size() - 1]; count += tmp.count*(tmp.count - 1)/2; stack.pop_back(); if(stack.size()) count += 2 * tmp.count; if(stack.size()==1 &&stack[stack.size()-1].count==1) count-=tmp.count; } cout << count<<endl; } return 0; }