Question-
Sunderland capital consists of n hills, forming a straight line. 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 straight line connecting the two hills there was no hill higher than any of the two. 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.
Input
The first line of the input data contains an integer number n (3 ≤ n ≤ 106), n — the amount of hills in the capital. The second line contains n numbers — heights of the hills. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Constraints
3 ≤ n ≤ 106
All height numbers are integer and lie between 1 and 109
SAMPLE INPUT
4
2 3 2 1
SAMPLE OUTPUT
3
Explanation
Required Pairs are (1,2), (2,3) and (3,4) hence output is 3.
Issue-
Wrong answer.
My logic-
Find next greater and previous greater element for each element.
For each parent element run from element to next greater and if any element in between has previous greater in front of parent element break loop.
Add 1 to ans for each iteration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include<iostream>
#include<stack>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
stack<int>s;
int ng[n],pg[n];
for(int i=0;i<n;i++)
{
if(s.empty())
{
s.push(i);
continue;
}
while(!s.empty() && arr[i]>arr[s.top()])
{
ng[s.top()]=i;
s.pop();
}
s.push(i);
}
while(!s.empty())
{
ng[s.top()]=-1;
s.pop();
}
for(int i=n-1;i>=0;i--)
{
if(s.empty())
{
s.push(i);
continue;
}
while(!s.empty() && arr[i]>arr[s.top()])
{
pg[s.top()]=i;
s.pop();
}
s.push(i);
}
while(!s.empty())
{
pg[s.top()]=-1;
s.pop();
}
long long int ans=0;
for(int i=0;i<n-1;i++)
{
int lim=ng[i];
ans++;
if(lim==-1)
{
for(int j=i+2;j<n;j++)
{
if(pg[j]>i)
break;
else
ans++;
}
}
else
{
for(int j=i+2;j<=lim;j++)
{
cout<<i<<" "<<j<<endl;
if(pg[j]>i)
break;
else
ans++;
}
}
}
cout<<ans;
return 0;
}
|