【NOIP2013提高组】花匠

这里写图片描述

题目很明显是要找一个锯齿形的序列。对于连续下降或上升的子序列,只能留下其中任意一个才能形成,于是可以直接找拐点,拐点个数+1就是最长锯齿序列的长度。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cctype>
#include<vector>
using namespace std;
int n,a[100005]={0};

void read(int &x)
{
    x=0;
    bool ok=0;
    char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')
    {
        ch=getchar();
    }
    while((ch>='0'&&ch<='9')||ch=='-')
    {
        if(ch=='-') ok=1;
        else x=x*10+ch-'0';
        ch=getchar();
    }
    if(ok) x=-x;
}

void in()
{
    read(n);
    for(int i=1;i<=n;i++) read(a[i]);
}

void task()
{
    int ans1=1,ans2=1;
    bool ok=0;
    for(int i=2;i<=n;i++)
    {
        if(!ok&&a[i]>a[i-1])
        {
            ans1++;
            ok=1;
        }
        if(ok&&a[i]<a[i-1])
        {
            ans1++;
            ok=0;
        }
    }
    ok=1;
    for(int i=2;i<=n;i++)
    {
        if(!ok&&a[i]>a[i-1])
        {
            ans2++;
            ok=1;
        }
        if(ok&&a[i]<a[i-1])
        {
            ans2++;
            ok=0;
        }
    }
    printf("%d",max(ans1,ans2));
}

int main()
{
    freopen("in.txt","r",stdin);
    in();
    task();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35546348/article/details/52421860