Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
The first line of the input data contains an integer number n (3 ≤ n ≤ 106), n — the amount of hills around the capital. The second line contains n numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Print the required amount of pairs.
5 1 2 4 5 3
7
首先对把这个环变为行,将最大的放在首尾两端,便于后续处理。然后,遍历,记录下左右第一个严格比自己大的位置,以及这之间与自己相等的数目。对于两个不相等的点,由于都是找比自己大的,就避免了由大到小又由小到大重复两次。对于相等的点,每增加一个相等的点,就相当于增加了之前点的数目的对数(开始是1个点0对)。这样也是不重复的。把这些对加起来。注意:对于左右比自己大的情况,如果左指向0,右指向n,0和n实际上是同一个数,对数只能加1而不是加2。
#include<cstdio>
#include<iostream>
using namespace std;
#define MAXN 1000001
int h[MAXN]={0},l[MAXN]={0},r[MAXN]={0},c[MAXN]={0};
int n;
void rotate(int offset){
int tmp[MAXN];
for(int i=0; i<n; i++){
tmp[i] = h[i];
}
for(int i=0; i<n; i++){
h[i] = tmp[(i+offset)%n];
}
h[n] = h[0];
}
void calInfo(){
int i;
l[0] = n;
for(i=1; i<n ; i++){
l[i] = i-1;
while(h[i]>h[l[i]])
l[i] = l[l[i]];
if(h[i] == h[l[i]]){
c[i] = c[l[i]]+1;
l[i] = l[l[i]];
}
}
r[n] = n;
for(i=n-1; i>=0; i--){
r[i] = i+1;
while(h[i]>h[r[i]])
r[i] = r[r[i]];
if(h[i] == h[r[i]]){
r[i] = r[r[i]];
}
}
}
long long getRes(){
long long res =0;
for(int i=1; i<n; i++){
if(h[i] < h[0]){
if(l[i] == 0 && r[i] == n){
res ++;
}else
res += 2;
}
res += c[i];
//cout<< c[i]<<"\t";
}
return res;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("data","r",stdin);
#endif
int max=0,maxp;
cin >> n;
for(int i = 0; i<n; i++){
cin >> h[i];
if(h[i]>max){
max = h[i];
maxp = i;
}
}
rotate(maxp);
calInfo();
cout<< getRes() <<endl;
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0;
}