洛谷 P3817:小A的糖果 ← 贪心算法
·
【题目来源】
https://www.luogu.com.cn/problem/P3817
【题目描述】
小 A 有 n 个糖果盒,第 i 个盒中有 ai 颗糖果。
小 A 每次可以从其中一盒糖果中吃掉一颗,他想知道,要让任意两个相邻的盒子中糖的个数之和都不大于 x,至少得吃掉几颗糖。
【输入格式】
输入的第一行是两个用空格隔开的整数,代表糖果盒的个数 n 和给定的参数 x。
第二行有 n 个用空格隔开的整数,第 i 个整数代表第 i 盒糖的糖果个数 ai。
【输出格式】
输出一行一个整数,代表最少要吃掉的糖果的数量。
【输入样例】
3 3
2 2 2
【输出样例】
1
【数据规模与约定】
对于 30% 的数据,保证 n≤20,ai,x≤100。
对于 70% 的数据,保证 n≤10^3,ai,x≤10^5。
对于 100% 的数据,保证 2≤n≤10^5,0≤ai,x≤10^9。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
typedef long long LL;
LL a[maxn];
LL ans;
int main() {
LL n,x;
cin>>n>>x;
for(int i=1; i<=n; i++) {
cin>>a[i];
}
for(int i=1; i<=n; i++) {
if(a[i-1]+a[i]>x) {
ans+=a[i-1]+a[i]-x;
a[i]-=a[i-1]+a[i]-x;
}
}
cout<<ans<<endl;
return 0;
}
/*
in:
6 1
1 6 1 2 0 4
out:
11
*/
更多推荐




所有评论(0)