当前位置:网站首页>关于判断单峰数组的几种方法
关于判断单峰数组的几种方法
2022-08-10 08:46:00 【Aidan 347】
由题意可知若要保证对于数组A的所有排列有 f(a) <= f(b),就要保证A数组是最优排列,也就是A数组中只能出现一个峰,只有这样才可以贪心地选择 [l, r] 范围内的数进行操作。
所以由此想到了一些判断单峰数组的方法:
方法一:
类似于双指针:从数组两端开始,对于左边若 a[i]>=a[i-1] , 左指针 ++;
对于右边若 a[i-1]>=a[i] , 右指针 --;
到最后如果左指针 >= 右指针(出现 l>r 是因为可能出现一段平整的数),则一定为单峰数组;
int l = 1, r = n;
for (int i = 1; i < n;)
{
if (a[i + 1] >= a[i])
{
i++;
l = i;
}
else
break;
}
for (int i = n; i > 1;)
{
if (a[i - 1] >= a[i])
{
i--;
r = i;
}
else
break;
}
if (l >= r)
{
cout << "YES" << endl;
return;
}
else
{
cout << "NO" << endl;
return;
}
方法二:
用flag标记:(flag初始为false表示未出现峰) ,从前往后遍历数组,若出现 a[i] > a[i+1] 说明在i处已经出现过一个峰,此时将flag标记为true(表示出现过峰),在这之后如果出现 a[i] < a[i+1] 的上升状态,说明在这之后必然要再出现一个峰
bool flag = false;
for (int i = 1; i < n; i++)
{
if (!flag && a[i] > a[i + 1])
flag = true;
else if (flag && a[i] < a[i + 1])
{
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
return;
方法三:
当然不是我想到的
Submission #167245781 - Codeforces
既然是单峰,那么只有一次连续上升的机会,所以计算从头开始的上升增量,最后判断上升增量是否等于最高的峰(若只有一个峰,就可以保证上升增量严格等于最高峰)
看到这个思路直接ORZ!!
for (int i=1;i<=n;i++)
{
cin>>a[i];
if (a[i]>a[i-1])
{
fa+=a[i]-a[i-1];
}
fb=max(fb,a[i]);
}
if (fa==fb) cout<<"YES\n";
else cout<<"NO\n";
边栏推荐
- Rust learning: 6.5_Array of composite types
- mySQL add, delete, modify and check advanced
- How AliExpress sellers seize product search weight
- 大体来讲,网站会被攻击分为几种原因
- UGUI—事件,iTween插件
- DAY25:逻辑漏洞
- The precise effect of network integration promotion outsourcing in the era of Internet of Things-Shenzhen Win-Win World News
- 协同工具满足70%-90%的工作需求,成为企业香饽饽
- Question brushing tool h
- 【Unity入门计划】制作RubyAdventure03-使用碰撞体&触发器实现世界交互
猜你喜欢
明明加了唯一索引,为什么还是产生重复数据?
ShardingSphere入门
CV+Deep Learning——网络架构Pytorch复现系列——classification(三:MobileNet,ShuffleNet)
J9 Number Theory: Macro Analysis of DAO Characteristics
不要把公司当成家,被通知裁员时会变得不幸...
DAY25: Logic Vulnerability
不想再干会计了,蝶变向新,勇往直前,最后成功通过转行测试实现月薪翻倍~
Solve the problem that the win10win7win8 system cannot find the specified module and cannot register the desert plug-in
Docker搭建Mysql一主一从
00后女孩月薪3200,3年买两套房,这个程序员变现新风口千万要把握住
随机推荐
【OAuth2】十九、OpenID Connect 动态客户端注册
Day37 LeetCode
DAY26:GetShell专题
[OAuth2] Nineteen, OpenID Connect dynamic client registration
Rust learning: 6.4_ enumeration of composite types
dayjs-----时间格式化
11111
幂次方(暑假每日一题 20)
2022-08-01 网工进阶(二十三) VLAN高级技术-VLAN聚合、MUX VLAN
The sixteenth day & the basic operation of charles
debezium-connector-mysql拉起docker报错:debezium启动docke
明明加了唯一索引,为什么还是产生重复数据?
Mongo的简单操作-数据库用户的查询、创建与删除
iwemeta元宇宙:阿里首任COO:如何打造销售铁军
Pieces of TensorFlow 2.9 (1)
Compilation failure:找不到符号
ARM Architecture 2: Processor Core and Assembly Instruction Set
iwemeta metaverse: Ali's first COO: how to build a sales force
设计分享|基于单片机的从左到右流水灯
[机缘参悟-65]:《兵者,诡道也》-7-三十六计解读-败战计