您的位置:首页 > 其它

HDU 5583 Kingdom of Black and White (暴力)

2017-08-27 09:41 267 查看


Kingdom of Black and White

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 0    Accepted Submission(s): 0

Problem Description

In the Kingdom of Black and White (KBW), there are two kinds of frogs: black frog and white frog.

Now N 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 T,
which indicates the number of test cases.

Every test case only contains a string with length N,
including only 0 (representing

a black frog) and 1 (representing
a white frog).

⋅ 1≤T≤50.

⋅ for
60% data, 1≤N≤1000.

⋅ for
100% data, 1≤N≤105.

⋅ the
string only contains 0 and 1.

 

Output

For every test case, you should output "Case #x: y",where x indicates
the case number and counts from 1 and y is
the answer.

 

Sample Input

2
000011
0101

 

Sample Output

Case #1: 26
Case #2: 10

题意:给出一些01字符串,要求改变某个字符(0->1or1->0)使得所有连续切相同的字符构成的子串的长度的平方和最大,并求出这个最大值。

思路:首先考虑特殊情况,所有字符都相同,这时结果直接就是字符串长度的平方。先暴力求出原字符串的结果,记为sum,并保存每一个连续相同子串的长度,其余大致分为两种情况,第一,找出所有连续字符相同子串中长度最长的,假设长度为x,(可能有多个,每个都要考虑,取结果最大的)假设旁边的最小长度为y,最大值就为变成x+1,y-1后的结果,比sum大出({(x+1)^2+(y-1)^2}-{x^2+y^2})2*(x-y+1)(注意考虑首尾的边界情况);第二,假设某个连续相同子串的长度为1,(可能有多个,每个都要考虑,取结果最大的,前后子串长度分别为x,y;最大值就是这三段子串合为一体的情况,结果比sum大出({(x+y+1)^2}-{(x^2+1+y^2)})2(x+y)+2*x*y(也要注意首尾边界情况,但是这里可以统一起来);取两种情况的最大值就可以了。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1e5+10;
char s[maxn];
int cnt[maxn];

int main()
{
int t,cas=1;
scanf("%d",&t);
while(t--)
{
memset(cnt,0,sizeof(cnt));///每次都要初始化为0,否则会出错。
scanf("%s",s);
int id=1,near,l=strlen(s);
long long sum=0,tmp,ans=0,len=1,mx=0;
for(int i=1; i<l; i++)
{
if(s[i]==s[i-1])
{
len++;
}
else
{
cnt[id++]=len;
mx=max(mx,len);
sum+=len*len;
len=1;
}
}
cnt[id++]=len;
mx=max(mx,len);
sum+=len*len;
if(id==2) printf("Case #%d: %lld\n",cas++,sum);
else
{
for(int i=1; i<id ; i++)
{
if(mx==cnt[i])
{
if(i==1) near=cnt[i+1];
else if(i==id-1) near=cnt[i-1];
else near=min(cnt[i-1],cnt[i+1]);
tmp=sum+2*(mx-near+1);
ans=max(ans,tmp);
}
}

for(int i=1; i<id; i++)
{
if(cnt[i]==1)
{
tmp=sum+(long long )2*cnt[i-1]*cnt[i+1]+2*(cnt[i-1]+cnt[i+1]);
ans=max(ans,tmp);
}
}
printf("Case #%d: %lld\n",cas++,ans);
}
}
}

参考文章:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: