N人们排队等着参加音乐会。人们等得很无聊,于是他们转身去排队寻找熟悉的人。
如果两个人A和B并排站在一起,或者如果他们中间没有人比A或B高,那么他们可以看到对方。编写一个程序,确定可以看到彼此的成对人数。
输入格式:
第一行输入包含一个整数N(1≤N≤500000),排队的人数。
以下N行中的每一行都包含一个整数,即一个人的身高(以纳米为单位)。
每个人的身高都将小于231纳米。高度是按照人们排队的顺序给出的。
输出格式:
输出可以看到对方的成对人数
输入样例:
7 2 4 1 2 2 5 1
输出样例:
10
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
栈限制
8192 KB
#include <bits/stdc++.h>
using namespace std;
stack<int> st;
int main(){
int n;
cin>>n;
int x;
int counts=0;
for(int i=0;i<n;i++){
cin>>x;//2 1;4
if(st.empty()||st.top()>=x){
if(!st.empty()&&st.top()==x){
counts++;
}
counts++;
st.push(x);
}else{
while(!st.empty()&&st.top()<=x){
st.pop();
counts++;
}
counts--;
if(!st.empty()&&st.top()==x){
counts++;
}
counts++;
st.push(x);
}
}
cout<<counts;
return 0;
}