defend the castle
#include <stdio.h>
#include <malloc/malloc.h>
typedef struct node {
int data;
struct node* next;
struct node* pre;
} Node;
int normalvalid(Node* from,Node* to)
{
int valid = 1;
int max = 0;
Node*p = from->next;
max = p->data;
while (p->data <= from->data && p!=to) {
if (p->data > max) max = p->data;
p = p->next;
}
if (p == to && to->data >max) valid = 1;
else valid = 0;
return valid;
}
int reversevalid(Node* from,Node* to)
{
int valid = 1;
int max = 0;
Node*p = from->pre;
max = p->data;
while (p->data <= from->data && p!=to) {
if (p->data > max)max = p->data;
p = p->pre;
}
if (p == to && to->data >max) valid = 1;
else valid = 0;
return valid;
}
int scan(Node* head)
{
int num = 0;
Node* start = head;
Node* next = start->next->next;
while (start->next != head) {
while (next != start->pre) {
if (normalvalid(start, next) || reversevalid(next, start))
num ++;
next = next->next;
}
start = start->next;
}
next = start->next->next;
while (next != start->pre) {
if (normalvalid(start, next) || reversevalid(next, start))
num ++;
next = next->next;
}
start = start->next;
return num;
}
int main(int argc, const char * argv[]) {
Node* head=(Node*)malloc(sizeof(Node));;
Node* pre;
Node* next = NULL;
int n;
pre = head;
scanf("%d",&n);
int data;
for (int i = 0 ; i < n; i ++) {
scanf("%d",&data);
pre->data = data;
if (data && i <n-1 ) {
next = (Node*)malloc(sizeof(Node));
pre->next = next;
next->pre = pre;
pre = next;
}
}
next->next = head;
head->pre = next;
printf("%d",n + scan(head));
return 0;
}