Flipping Game(暴力或贪心)
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.
Input
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.
Output
Print an integer — the maximal number of 1s that can be obtained after exactly one move.
Examples
Input
5
1 0 0 1 0
Output
4
Input
4
1 0 0 1
Output
4
Note
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.
题意: 找个连续区间,把区间中的数字反转(0变1,1变0),问最多能有几个1
思路: 第一种就是暴力找,开个三层for循环,第二种就是贪心,不管用那种方法,都是先统计本来有几个1,然后找连续区间中反转后最多有几个1,相加即可
AC代码:
暴力:
#include<stdio.h>
#include<string.h>
int a[1100],book[1100];
int main()
{
int n,i,j,k=0,x=0,maxx=0,t=0;
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
if(a[i]==1)
t++;
}//printf("%d***\n",k);
if(t==0)//特判,如果全是0,反转后就全是1
{
printf("%d",n);
return 0;
}
if(t==n)//如果全是1,总有一个要反转成0,那最多就n-1个1
{
printf("%d",n-1);
return 0;
}
for(i=0; i<n; i++)
for(j=i; j<n; j++)
{
memset(book,0,sizeof(book));
for(k=i; k<=j; k++)
book[a[k]]++;//统计区间中有几个0,几个1
if(book[0]>book[1])//区间中0多,反转后就1多
{
if(maxx<t+book[0]-book[1])
maxx=t+book[0]-book[1];//maxx记最多有几个1
}
}
printf("%d",maxx);
return 0;
}
贪心:
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int i,ans=0,maxx=-1,m,v=0;
for(i=0; i<n; i++)
{
scanf("%d",&m);
if(m==0)
{
ans++;
if(ans>maxx)
maxx=ans;//统计反转前区间中最多有几个0
}
else
{
v++;//v++和注释部分都是统计反转前有几个1,选其一即可
ans--;
if(ans<0)
ans=0;
}
// if(ans==0||ans<maxx) //如00011110这种情况
// v+=m; //不能写成v++,如00011110
}
printf("%d\n",maxx+v);
return 0;
}