Kingdom of Black and White
Time Limit: 20 Sec
Memory Limit: 256 MB
题目连接
http://acm.hdu.edu.cn/showproblem.php?pid=5583
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
HINT
题意
给你一个只含有01的字符串,然后这个串的权值就是每一段连续的0或1的长度的平方和,然后你可以修改一个数,使得这个数变成0,或者使这个数变成1
然后问你最大权值能为多少
题解:
不能直接暴力枚举每一位,但是我们可以枚举每一个连通块就好了
每个连通块毫无疑问,只会修改最左边或者最右边的位置,然后直接扫一遍就行了
代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<math.h>
#include<vector>
using namespace std; string s;
int main()
{
int t;scanf("%d",&t);
for(int cas=;cas<=t;cas++)
{
cin>>s;
int flag = -;
vector<long long> Q;
int len = ;
for(int i=;i<s.size();i++)
{
if(s[i]-''!=flag)
{
Q.push_back(len);
len = ;
flag = s[i]-'';
}
else
len++;
}
Q.push_back(len);
Q.push_back();
long long Ans = ;
for(int i=;i<Q.size()-;i++)
Ans += Q[i]*Q[i];
long long Ans2 = Ans;
for(int i=;i<Q.size()-;i++)
{
long long tmp = ;
if(Q[i]==)
Ans2 = max(Ans2,Ans-Q[i-]*Q[i-]-Q[i]*Q[i]-Q[i+]*Q[i+]+(Q[i-]+Q[i+]+)*(Q[i-]+Q[i+]+));
else
{
Ans2 = max(Ans2,Ans-Q[i-]*Q[i-]-Q[i]*Q[i]+(Q[i-]+)*(Q[i-]+)+(Q[i]-)*(Q[i]-));
Ans2 = max(Ans2,Ans-Q[i+]*Q[i+]-Q[i]*Q[i]+(Q[i+]+)*(Q[i+]+)+(Q[i]-)*(Q[i]-));
}
}
printf("Case #%d: %lld\n",cas,Ans2);
}
}