洛谷 P5650 【基础字符串练习题】

P5650

题意:

给你一个零一串,然后让你找一个连续的字串,求这个字串内的0的个数减去1的个数最大.

小思路:

我们将0看做1,然后将1看做-1,然后求一下前缀和.

求前缀和的时候我们将当前这个位置的前缀和如果为负数,那么我们就将他赋成0
因为如果是负数那么他对后边的贡献就是负数,比零都要小,所以我们赋值成0,

然后我们把每一段的前缀和与ans去一个max,最后的时候输出ans就好了

需要注意的是,题目中要求字串是非空的,我们就必须要选择一个字串

因为如果都是1的话,那么我们不得不选一个,直接输出-1就好

code
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

#define N 100010
#define M 1010

using namespace std;
int n, num[N];
char ch[N];

int main() {
	gets(ch);
	int len = strlen(ch);
	for (int i = 0; i < len; i++) 
		if (ch[i] == '1') num[i + 1] = -1;
		else num[i + 1] = 1;
	int ans = -100000;
	for (int i = 1; i <= len; i++) {
		num[i] += num[i - 1];
		if (num[i] < 0) num[i] = 0;
		ans = max(ans, num[i]);
	}
	if (ans == 0) puts("-1");
	else cout << ans;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章