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 (1≤k≤N)(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 l≤x≤rl≤x≤r.
Find the minimum number of watering operations required to satisfy the condition.
Constraints
- 1≤N≤1001≤N≤100
- 0≤hi≤1000≤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; }
原文地址:https://www.cnblogs.com/pengge666/p/11599573.html
时间: 2024-10-05 01:51:43