题干如下:
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.
The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a1, a2, ..., an. It is guaranteed that each of those n values is either 0 or 1.
Print an integer — the maximal number of 1s that can be obtained after exactly one move.
5
1 0 0 1 0
4
4
1 0 0 1
4
In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1].
In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
(可以用浏览器自带的翻译工具或者其他小组件进行翻译~)
首先对题干进行分析:通过反转一段区间内的数字,使整串数字的‘1’的个数最多。
不妨设置两个指针进行区间的划分。一个指针从头到尾遍历,走完后第二个指针再从头移动一位,让第一个指针再进行数字串的遍历。这也就是接下来的代码中双重循环的含义。再对每个反转的串中的1的个数相加取出最大值即可。在简单构思后发现要写到三重循环,n给到了100范围,故可以实现。(好耶~)
下面是代码:
#include <iostream>
#include <algorithm>
using namespace std;
int n,maxn,sum1;
int res;
int arr[100010],brr[100010];//原数组与反转后数组
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++ )
{
cin >> arr[i];
}
for(int i = 1; i <= n; i ++ )
{
for(int j = i; j <= n; j ++ )
{//以上为双重循环遍历数组内各个区间
int sum = 0;
for(int k = 1; k <= n; k ++ )
{//记录反转后的情况
brr[k] = arr[k];//初始化
}
for(int k = i; k <= j; k ++ )
{
brr[k] = 1 - brr[k];//反转
}
for(int k = 1; k <= n; k ++ )
{
sum += brr[k];
}
res = max(res,sum);//取出最大‘1’情况
}
}
cout << res << "\n";
return 0;
}
——————end——————
总结:自己做的还是不到位,第一遍做的时候一直在想将0,1全部找出多少个再看,但是多少有点抽象了,思维题的训练还是不够....
就这样罢(悲)。