The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:
- ti < ti + 1 for each odd i < n;
- ti > ti + 1 for each even i < n.
For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.
Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence.
The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice.
Print the number of ways to swap two elements exactly once in order to get a nice sequence.
5 2 8 4 7 7
2
4 200 150 100 50
1
10 3 2 1 4 1 4 1 4 1 4
8
9 1 2 3 4 5 6 7 8 9
0
#include <bits/stdc++.h>
#define MOD 1000000007
#define maxn 150005
#define INF 1e18
using namespace std;
typedef long long ll;
int num[maxn], n;
vector<int> v;
bool judge(int i){
if(i&1){
if((i == 1 || num[i] < num[i-1]) && (i == n || num[i] < num[i+1]))
return true;
return false;
}
if(num[i] > num[i-1] && (i == n || num[i] > num[i+1]))
return true;
return false;
}
int main(){
// freopen("in.txt", "r", stdin);
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", num+i);
int cnt = 0;
for(int i = 2; i <= n; i += 2){
if(num[i] <= num[i-1] || (i < n && num[i] <= num[i+1])){
cnt++;
v.push_back(i);
}
}
if(cnt > 3)
puts("0");
else if(cnt == 2){
int k1 = v[0], k2 = v[1];
int ans = 0;
if(k2 - k1 == 2){
for(int i = 1; i <= n; i++)
for(int j = k1-1; j <= k2+1; j++)
if(i != k1 && i != k2 && j <= n){
swap(num[i], num[j]);
if(judge(k1) && judge(k2) && judge(i))
ans++;
swap(num[i], num[j]);
}
}
else{
for(int i = k1-1; i <= k1+1; i++)
for(int j = k2-1; j <= k2+1; j ++)
if(j <= n){
swap(num[i], num[j]);
if(judge(k1) && judge(k2))
ans++;
swap(num[i], num[j]);
}
}
printf("%d\n", ans);
}
else if(cnt == 1){
int ans = 0;
int k = v[0];
for(int i = 1; i <= n; i++)
for(int j = k-1; j <= k+1; j++){
if(i != k && j <= n){
swap(num[i], num[j]);
if(judge(i) && judge(k)){
ans++;
}
swap(num[i], num[j]);
}
}
printf("%d\n", ans);
}
else if(cnt == 3){
int ans = 0;
int k1 = v[0], k2 = v[1], k3 = v[2];
if(k1 == k2 - 2){
swap(num[k1+1], num[k3]);
if(judge(k1) && judge(k2) && judge(k3))
ans++;
swap(num[k1+1], num[k3]);
}
if(k2 == k3 - 2){
swap(num[k1], num[k2+1]);
if(judge(k1) && judge(k2) && judge(k3))
ans++;
}
cout << ans << endl;
}
return 0;
}