洛谷 P5019 铺设道路 & [NOIP2018提高组](贪心)

题目链接

https://www.luogu.org/problem/P5019

解题思路

一道典型的贪心题。

假设从左往右填坑,如果第i个深与第i+1个,那么第i+1个就不需要额外填;

如果第i+1个大于第i个,就需要填i+1-i的深度,所以就相当于把>0的差分数组加起来就AC了。

AC代码

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 int a[100005];
 5 long long ans;
 6 int main(){
 7     int n;
 8     cin>>n;
 9     for(int i=1;i<=n;i++){
10         scanf("%d",&a[i]);
11         if(a[i]>a[i-1]){
12             ans+=a[i]-a[i-1];
13         }
14     }
15     cout<<ans;
16     return 0;
17 }

//NOIP2018提高组Day1 t1

posted @ 2019-07-29 20:46  尹昱钦  阅读(253)  评论(0编辑  收藏  举报