AtCoder Beginner Contest 116 C题 【题意:可以在任意区间【L,R】上加1,求通过最少加1次数得到题目给定的区间】】{思维好题}

C - Grand Garden

In a flower bed, there are NN flowers, numbered 1,2,......,N1,2,......,N. Initially, the heights of all flowers are 00. You are given a sequence h={h1,h2,h3,......}h={h1,h2,h3,......} as input. You would like to change the height of Flower kk to hkhk for all kk (1kN)(1≤k≤N), by repeating the following "watering" operation:

  • Specify integers ll and rr. Increase the height of Flower xx by 11 for all xx such that lxrl≤x≤r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

  • 1N1001≤N≤100
  • 0hi1000≤hi≤100
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN
h1h1 h2h2 h3h3 ............ hNhN

Output

Print the minimum number of watering operations required to satisfy the condition.

Input

4
1 2 2 1

Output

2

Input

8
4 23 75 0 23 96 50 100

Output

221

题意:可以任意在区间【L,R】上加1,求通过最少次数得到题目给定的区间的值】

AC代码:

#include<bits/stdc++.h>

using namespace std;
#define int long long
int arr[152052];
signed  main(){
     int ans=0;
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
        scanf("%lld",&arr[i]);
    int temp=arr[1];
    for(int i=1;i<=n;i++){
        if(i==n){  // 特判一下
            ans+=max(arr[i],temp);
        }else{
            if(arr[i]>=temp){
                temp=arr[i];
            }else{
                ans+=abs(arr[i]-temp);// 需要减去多加的数
                temp=arr[i];
            }
        }
    } 
    cout<<ans;
    return 0;
}

代码2

#include<bits/stdc++.h>

using namespace std;
#define N 515155
int arr[N];

int main(){
  int n;
  cin>>n;
  int ans=0;
  scanf("%d",&arr[1]);
  if(n==1){
    cout<<arr[1];
    return 0;
  }
  int temp=arr[1];
  for(int i=2;i<=n;i++){
    scanf("%d",&arr[i]);
    if(i==n){
      ans+=max(temp,arr[i]);
      break;
    }
    if(arr[i]<temp){
      ans+=temp-arr[i];
      temp=arr[i];
    }else{
      temp=arr[i];
    }
  }
  cout<<ans; 
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/pengge666/p/11599573.html