洛谷P1181 Java
程序员文章站
2022-07-16 10:51:26
...
题目出处点这里
思路:每一段的和要尽量接近M,也就是说第一段的和尽量接近M,第二段的和尽量接近M,第三段的和尽量接近M…
代码如下:
package greedy;
import java.util.Scanner;
public class P1181 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int sum = 0,ans = 1;//ans=1因为第一段算不进去
for (int i = 0; i < N; i++) {
int a = sc.nextInt();
if (sum + a <= M) {
sum = sum + a;
}else {
ans++;
sum = a;
}
}
System.out.println(ans);
}
}