小红不想做平衡树:
思路解析:
好数组的定义为 恰好翻转一个区间是得,这个区间变为升序的。
那么就有五种情况:
1.本身数组就升序的, 翻转一个长度为1的区间后,数组仍为升序
2.本身数组就降序的,翻转整个区间后,数组为升序。
3.数组先升序后降序,翻转降序区间后,数组变为升序 (需要满足降序区间最小元数大于升序区间最大元数)
4.数组先降序后升序,翻转降序区间后,数组变为升序,(需要满足降序区间最大元数小于升序区间最小元数)
5.数组先升序再降序后升序,翻转降序区间后数组变为升序,(需要满足3和4的条件)
代码实现:
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int inf = (int) 1e9;
public static void main(String[] args) throws IOException {
int t = 1;
while (t > 0) {
solve();
t--;
}
w.flush();
w.close();
br.close();
}
static int n;
static int[] pre;
static int[] suf;
static int[] a;
static long ans = 1;
public static void solve() {
n = f.nextInt();
pre = new int[n+1];
suf = new int[n+1];
a = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = f.nextInt();
}
pre[1] = 1;
for (int i = 2; i <= n; i++) {
if (a[i] > a[i-1]) pre[i] = pre[i-1];
else pre[i] = i;
ans += i - pre[i] + 1;
}
suf[n] = n;
for (int i = n-1; i > 0; i--) {
if (a[i] < a[i+1] ) suf[i] = suf[i+1];
else suf[i] = i;
}
int i = 1;
while (i <= n){
int j = i;
while (j < n){
if (a[j] > a[j+1]) j++;
else break;
}
if (j > i) calc(i, j);
i = j+1;
}
w.println(ans);
}
// 全升序
// 全降序
// 先升序后降序
// 先降序后升序
// 先升序, 后降序, 再升序
public static void calc(int l, int r){
int len = (r - l + 1);
ans +=(long) len * (len - 1) / 2; // 全降序
for (int i = l; i <= r; i++) { // 先升序 后降序
if (a[i] <= a[l-1] || l == 1){
break;
}
ans += l - pre[l];
}
ans -= l - pre[l];
for (int i = r; i >= l; i--) { // 先降序 后升序
if (a[i] >= a[r+1] || r == n) break;
ans += suf[r] - r;
}
ans -= suf[r] - r;
if (l > 1 && r < n && a[l] < a[r+1] && a[r] > a[l-1]){
ans += (long) (l - pre[l]) * (suf[r] - r);
}
}
static PrintWriter w = new PrintWriter(new OutputStreamWriter(System.out));
static Input f = new Input(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static class Input {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Input(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
}