这个题再次证明了单调栈的力量
简单 单调栈 类似上次校内选拔消砖块
一堆牛面朝右排 给出从左到右的 问每个牛的能看到前面牛发型的个数之和
//re原因 因为在执行pop的时候没有判断empty 程序崩溃
转换下思想 我们可以求每个牛被后面的牛看见的次数之和
维护一个单调减栈 size为能看到当前准备入栈的发型的牛个数
so 解决了 代码超短

1 #include<cstdio> 2 #include<map> 3 //#include<bits/stdc++.h> 4 #include<vector> 5 #include<stack> 6 #include<iostream> 7 #include<algorithm> 8 #include<cstring> 9 #include<cmath> 10 #include<queue> 11 #include<cstdlib> 12 #include<climits> 13 #define PI acos(-1.0) 14 #define INF 0x3f3f3f3f 15 using namespace std; 16 typedef long long ll; 17 typedef __int64 int64; 18 const ll mood=1e9+7; 19 const int64 Mod=998244353; 20 const double eps=1e-9; 21 const int N=2e7+10; 22 const int MAXN=1e5+5; 23 inline void rl(ll&num){ 24 num=0;ll f=1;char ch=getchar(); 25 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 26 while(ch>='0'&&ch<='9')num=num*10+ch-'0',ch=getchar(); 27 num*=f; 28 } 29 inline void ri(int &num){ 30 num=0;int f=1;char ch=getchar(); 31 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 32 while(ch>='0'&&ch<='9')num=num*10+ch-'0',ch=getchar(); 33 num*=f; 34 } 35 int getnum()//相邻的个位整数输入 如想分别保存1234 输入连续的1234 a[i]=getnum();就可以实现 36 { 37 char ch=getchar(); 38 while((ch<'0' || ch>'9') && ch!='-') 39 ch=getchar(); 40 return (ch-'0'); 41 } 42 inline void out(int x){ if(x<0) {putchar('-'); x*=-1;}if(x>9) out(x/10); putchar(x%10+'0'); } 43 int main() 44 { 45 stack<ll> s; 46 int n; 47 while(scanf("%d",&n)==1) 48 { 49 ll tem,ans=0; 50 while(n--) 51 { 52 rl(tem); 53 if(s.empty()) 54 { 55 s.push(tem); 56 } 57 else{ 58 while(!s.empty()&&s.top()<=tem) s.pop();//看见前方的牛了 59 s.push(tem); 60 } 61 ans+=s.size()-1; 62 } 63 cout<<ans<<endl; 64 while(!s.empty())s.pop(); 65 } 66 return 0; 67 }