#include #define RISING true #define FALLING false unsigned long long totalCount; int peakValleyPos[10000]; int powers[100000]; void find_pairs(int startPeakNum, int endPeakNum) { if (startPeakNum + 2 == endPeakNum) { totalCount += (peakValleyPos[endPeakNum] - peakValleyPos[startPeakNum + 1]) * (peakValleyPos[startPeakNum + 1] - peakValleyPos[startPeakNum]) - 1; return; } int maxInsidePeak = startPeakNum + 2; int i = maxInsidePeak + 2; while (i < endPeakNum) { if (powers[i] > powers[peakValleyPos[maxInsidePeak]]) { maxInsidePeak = i; } i += 2; } int countLeft = 0, countRight = 0; i = startPeakNum; while (powers[i] >= powers[peakValleyPos[maxInsidePeak]]) { countLeft++; i++; } i = endPeakNum; while (peakValleyPos[i] >= powers[peakValleyPos[maxInsidePeak]]) { countRight++; i--; } totalCount += countLeft * countRight; find_pairs(startPeakNum, maxInsidePeak); find_pairs(maxInsidePeak, endPeakNum); } int main() { int N; int newPeakValleyPosIndex = 1; bool direction = FALLING; int firstPeakPos = 0, lastPeakPos = 0; peakValleyPos[0] = 0; scanf("%d", &N); scanf("%d", &powers[0]); scanf("%d", &powers[1]); if (powers[0] < powers[1]) { direction = RISING; firstPeakPos = 1; } for (int i = 2; i < N; i++) { scanf("%d", &powers[i]); if (powers[i] > powers[i - 1] && direction == FALLING) { peakValleyPos[newPeakValleyPosIndex++] = i - 1; direction = RISING; } else if (powers[i] < powers[i - 1] && direction == RISING) { peakValleyPos[newPeakValleyPosIndex++] = i - 1; direction = FALLING; } } if (direction == RISING) { peakValleyPos[newPeakValleyPosIndex] = N - 1; lastPeakPos = newPeakValleyPosIndex; } else { lastPeakPos = newPeakValleyPosIndex - 1; } find_pairs(firstPeakPos, lastPeakPos); totalCount += N - 1; printf("%lld", totalCount); }