AtCoder Grand Contest 013 A-Sorted Arrays ( 贪心

Sorted Arrays

Description

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?

Input

Input is given from Standard Input in the following format:

N
A1 A2 … AN

Output

Print the minimum possible number of subarrays after division of A.

Sample Input

6
1 2 3 2 2 1

Sample Output

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Hint

1≤N≤105
1≤Ai≤109
Each Ai is an integer.

题意

找出一个数组内 非递减数列,非递增数列 一个有几个;

题解:

明显的贪心思想
蒟蒻在多开个数组进行标记

AC代码

#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
int n, arr[N], dp[N];
int main()
{
    int n;
    scanf("%d",&n);
    for(int i = 0;i < n; i++) 
        cin>>arr[i];
    int ans, res;
    for(int i = 0;i < n; i++) {
        dp[i+1] = INF;
        if(i>=1 && arr[i-1]>arr[i]) ans = i;
        else dp[i+1] = dp[ans]+1;
        if(i>=1 && arr[i-1]<arr[i]) res = i;
        else dp[i+1] = min(dp[i+1],dp[res]+1); 
    }
    cout<<dp[n]<<endl;  
return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值