Luogu P1970 花匠

Luogu P1970 花匠

本质上就是找最长的波浪序列。
因为考虑到第一个必选,所以可以让$lst=h[1]$.
此外,注意到$n=1$是要特判,其他情况下显然$ansgeq 2$,所以把$dir$初始化为$-1$是很巧的操作,这保证了除第一个外至少有一个被选。

#include<bits/stdc++.h>

using namespace std;

int n,m,lst,dir=-1,newdir; //(new)dir记录方向:0下1上
int h[100010];

int main() {
	scanf("%d",&n);
	for(int i=1;i<=n;i++) {
		scanf("%d",&h[i]);
	}
	if(n==1) {
		printf("1");
		return 0;
	}
	m++;
	lst=h[1];
	for(int i=2;i<=n;i++) {
		if(h[i]==lst) {
			continue;
		}
		else if(h[i]<lst) {
			newdir=0;
		}
		else {
			newdir=1;
		}
		if(newdir!=dir) {
			m++;
			dir=newdir;
		}
		lst=h[i];
	}
	printf("%d",m);
	return 0;
}
原文地址:https://www.cnblogs.com/luoshui-tianyi/p/11681862.html