AcWing 2014. 岛(USACO 2012 US Open Bronze Division)

题目链接

思路:

  • 很容易想到对每个田地的高度进行从小到大的排序,再依次枚举每一个高度,看看海水涨到这个高度会不会对结果有什么影响。我们就看这个田地左右两边的田地的高度和它的关系,很容易看出只有这两种情况才会对结果有影响,-1的那三个图其实可能统一判断,具体见代码。

在这里插入图片描述

  • 但是这样有一个问题,就是可能出现这样的情况:中间有很多个相同高度的田,但是这些相同的其实可以看做一个田,对结果的影响是一样的,所以我们用到unique函数对初始高度进行去重
    在这里插入图片描述
  • 注意更新答案的时候,要判断是否是枚举到不同的高度了,unique去重后还可能出现这样的情况,因为unique函数只是“去掉”相邻重复的元素,所以这样的情况我们只能更新一次
    在这里插入图片描述

AC代码

#include<bits/stdc++.h>
#define rep(i,x,y) for(int i=x; i<=y; i++)
#define pre(i,x,y) for(int i=x; i>=y; i--)
#define ll long long
#define PII pair<int,int>
#define x0 x00000
#define y0 y00000
#define y1 y11111
#define x1 x11111
using namespace std;
const int N = 1e5+9;
int H[N];
struct node {
	int pos,h;
	bool operator<(const node &t)const {
		if(t.h!=h) return h<t.h;
		else return pos<t.pos;
	}
}nd[N];
int main() {
	int n;
	cin>>n;
	rep(i,1,n){
		int h;
		scanf("%d",&H[i]);
		//nd[i]={i+1,H[i]};
	}
	//这里去重很精辟 
	n=unique(H+1,H+n+1)-H-1;//去重 
	rep(i,1,n) nd[i]={i,H[i]};
	sort(nd+1,nd+n+1);
	int ans=1,tmp=1;
	rep(i,1,n){
		int p=nd[i].pos;
		if(H[p]<H[p+1] && H[p]<H[p-1]) tmp++;
		else if(H[p]>H[p+1] && H[p]>H[p-1]) tmp++;
		//要注意更新的时候,必须枚举到不同的高度后才能更新
		//unique只是去掉相邻重复的元素 
		if(nd[i].h!=nd[i+1].h) ans=max(ans,tmp);
	}
	printf("%d\n",ans);
	return 0;
}
posted @ 2022-08-28 08:43  翔村亲亲鸟  阅读(12)  评论(0编辑  收藏  举报