Problem Statement
Constraints
Input
Output
Sample Input 1
Sample Output 1
Sample Input 2
Sample Output 2
Sample Input 3
Sample Output 3
You are given an array A of length N. Your task is to divide it into several contiguous subarrays. Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order. At least how many subarrays do you need to divide A into?
- 1 \leq N \leq 10^5
- 1 \leq A_i \leq 10^9
- Each A_i is an integer.
Input is given from Standard Input in the following format:
N A_1 A_2 ... A_N
Print the minimum possible number of subarrays after division of A.
6 1 2 3 2 2 1
2
One optimal solution is to divide the array into [1,2,3] and [2,2,1].
9 1 2 1 2 1 2 1 2 1
5
7 1 2 3 2 1 999999999 1000000000
3
题意:判断非递减数列,非递增数列的和;
思路:循环跑一遍O(n),res标记是否确定flag的真假,flag标记非递增还是非递减;
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long LL;
using namespace std;
#define max_n 100005
int a[max_n];
int main()
{
int n,k=1,ans,i;
bool flag,res=false;
scanf("%d",&n);
scanf("%d",&a[0]);
if(n==1)
{
printf("1\n");
return 0;
}
ans=a[0];
for(i=1;i<n;i++)
{
scanf("%d",&a[i]);
if(!res)
{
if(a[i]>ans)
{
flag=true;
res=true;
ans=a[i];
}
else if(a[i]<ans)
{
flag=false;
res=true;
ans=a[i];
}
}
else
{
if(flag)
{
if(a[i]>=ans)
ans=a[i];
else
{
k++;
ans=a[i];
res=false;
}
}
else
{
if(a[i]<=ans)
ans=a[i];
else
{
k++;
ans=a[i];
res=false;
}
}
}
}
printf("%d\n",k);
return 0;
}