Kingdom of Black and White
Description
In the Kingdom of Black and White (KBW), there are two kinds of frogs: black frog and white frog.
Now frogs are standing in a line, some of them are black, the others are white. The total strength of those frogs are calculated by dividing the line into minimum parts, each part should still be continuous, and can only contain one kind of frog. Then the strength is the sum of the squared length for each part.
However, an old, evil witch comes, and tells the frogs that she will change the color of at most one frog and thus the strength of those frogs might change.
The frogs wonder the maximum possible strength after the witch finishes her job.
Input
First line contains an integer , which indicates the number of test cases.
Every test case only contains a string with length , including only (representing
a black frog) and (representing a white frog).
.
for 60% data, .
for 100% data, .
the string only contains 0 and 1.
Output
For every test case, you should output ” Case #x: y”,where indicates the case number and counts from and is the answer.
Sample Input
2
000011
0101
Sample Output
Case #1: 26
Case #2: 10
题意:有一串由0和1组成的串,然后至多改变里面一个字符(把0改成1或者把1改成0);然后这个串由0和1组成的每个部分的平方和最大,每个部分只有0或者1组成。
分析:直接模拟暴力,将这一串数字的每个部分的个数存起来,然后再遍历每一个部分,看改变一个数字后平方和会不会变大。最后将最大的输出来。
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
int main ()
{
int t;
scanf ("%d",&t);
char a[100005];
long long s[100005];
int p=0;
while (t--){
p++;
scanf ("%s",a);
int len=strlen(a);
int cnt=1;
memset (s,0,sizeof (s));
s[1]=1;
for (int i=1;i<len;i++){
if (a[i]==a[i-1]){
s[cnt]++;
}
else s[++cnt]++;
}
long long ans=0;
for (int i=1;i<=cnt;i++){
ans+=s[i]*s[i];
}
long long temp=0;
for (int i=1;i<=cnt;i++){
if (i==1){//第一个只能向右边改变
long long t1=pow(s[i]-1,2)+pow(s[i+1]+1,2)-pow(s[i],2)-pow(s[i+1],2);
if (temp<t1)temp=t1;
}
else if (i==cnt){//最后一个只能向左边改变
long long t1=pow(s[i]-1,2)+pow(s[i-1]+1,2)-pow(s[i],2)-pow(s[i-1],2);
if (temp<t1)temp=t1;
}
else {
long long t1,t2;
if (s[i]==1){//当这部分这有一个数时
t1=pow(s[i-1],2)+pow(s[i],2)+pow(s[i+1],2);
t2=pow(s[i]+s[i-1]+s[i+1],2);
temp=max(temp,t2-t1);
}
else {
//与左边
t1=pow(s[i]-1,2)+pow(s[i-1]+1,2)-pow(s[i],2)-pow(s[i-1],2);
if (temp<t1) temp=t1;
//与右边
t2=pow(s[i]-1,2)+pow(s[i+1]+1,2)-pow(s[i],2)-pow(s[i+1],2);
if (temp<t2) temp=t2;
}
}
}
printf("Case #%d: %lld\n",p,ans+temp);
}
return 0;
}