## 保卫方案

C_n_2  是表示，从这n个数中，取出不重复的对为  C_n_2，而如果左边数还在，则还要+ n 个对，因为 这n个数字分别要和这个最大的数进行配对，所以有n个，而右边如果也存在比他大的数的话，也是同理。

``````#include<iostream>
#include<cstdlib>
#include<ctime>
#include<stack>
using namespace std;
struct node{
int num;
int count;
node(int num){
this->num = num;
this->count = 1;
}
};
typedef long long ll;
int N;
int arr[1000000+100];
stack<node> stk;

int get_next(int id,int len){
return  id>=(len-1)?0:id+1;
}

void scanfArr(){
scanf("%d",&N);
for(int i=0;i<N;i++){
scanf("%d",&arr[i]);
}
}

void printfArr(){
for(int i=0;i<N;i++){
printf("%d ",arr[i]);
}
printf("\n");
}

ll getC_n_2(int n){
return n== 1? 0: (ll)n *(ll)(n-1)/(ll)2;
}

int main(){
scanfArr();

int max_idx = 0;
int max_num = arr[max_idx];
for(int i=0;i<N;i++){
if(arr[i]>max_num){
max_num = arr[i];
max_idx = i;
}
}

int idx = get_next(max_idx,N);
node a = node(arr[max_idx]);
stk.push(a);
ll sum = 0;
while(idx != max_idx){
node temp = stk.top();
if(arr[idx]>temp.num){
stk.pop();
sum += getC_n_2(temp.count);
sum +=temp.count;
if(!stk.empty()) sum+= temp.count;

if (!stk.empty() && arr[idx] == stk.top().num){
stk.top().count++;
}else{
node new_ = node(arr[idx]);
stk.push(new_);
}
}else if(arr[idx]<temp.num){
node new_ = node(arr[idx]);
stk.push(new_);
}else if( arr[idx] == temp.num){
stk.top().count++;
}
idx = get_next(idx,N);
}

while(!stk.empty()){
node temp = stk.top(); stk.pop();
sum+= getC_n_2(temp.count);
if(!stk.empty()){
sum+= temp.count;
node temp_no = stk.top();
if(temp_no.num == max_num){
sum+= temp_no.count>1? temp.count:0;
}else {
sum+= temp.count;
}
}
}

printf("%ld\n",sum);

return 0;
}``````