[贪心][题目][洛谷]P1181_数列分段Section_I

这个虽然不知道怎么证明,但是觉得从头到尾数一遍是可以完成这个动作的
ac代码
策略也是比较简单,从前往后数,在不超过M的情况下能数多少算多少,这样数出来的数作为一个分段
我想不出来这样一种情况,那就是在从前往后数完一次之后会导致错误发生的情况,这个找不到矛盾,可以让人更确信这个猜想,但如何证明呢?

#include <iostream>
#include <cstdio>
using namespace std;
int read() {
	int x = 0, f = 1; char c = getchar();
	while (c > '9' || c < '0') { c = getchar(); }
	while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
	return x * f;
}
int main() {
	int N, M; N = read(); M = read();
	int sum = 0; int ans = 0;
	for (int i = 1; i <= N; i++){
		int temp = read(); sum += temp;
		if (i < N && sum >= M) {
			ans++;
			if (sum == M)sum = 0;
			else sum = temp;
		}else if (i == N) {
			if (sum <= M)ans++;
			else ans += 2;
		}
	}
	printf("%d",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37456764/article/details/84331779
今日推荐