Kingdom of Black and White HDU - 5583
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或1)的串,然后求每段长度的平方和
现在可以最多修改一个位置,使得0变成1或者1变成0,问最终得到的最大值是多少
分析:
根据题意字符串一点可以分成[0][1][0][1][0][1]的形式,[0]代表一段全为0的连续段[1]同理
因此只需要贪心暴力每个边界,修改后取最大值即可
注意如果某段只有一个字符,那么修改后,就会使得前一段和后一段连成一个更长的段,因此这种情况,我们重新再判断一遍即可
code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
char s[100010];
ll a[100010];
int main(){
int t,cas = 0;
scanf("%d",&t);
while(t--){
scanf("%s",s);
ll cnt;
int n = 0;
int len = strlen(s);
cnt = 1;
ll sum = 0;
for(int i = 1; i < len; i++){
if(s[i] != s[i-1]){
sum += cnt * cnt;
a[n++] = cnt;
cnt = 1;
}
else{
cnt++;
}
}
sum += cnt * cnt;
a[n++] = cnt;
ll ans = sum;
//cout << sum << endl;
for(int i = 1; i < n; i++){
ll tmp = sum - a[i-1] * a[i-1] - a[i] * a[i];
ll tmp2 = tmp + (a[i-1] + 1) * (a[i-1] + 1) + (a[i] - 1) * (a[i] - 1);
ll tmp3 = tmp + (a[i-1] - 1) * (a[i-1] - 1) + (a[i] + 1) * (a[i] + 1);
tmp = max(tmp2,tmp3);
ans = max(ans,tmp);
//cout << i << ": " <<ans << endl;
}
//cout << "----------------" << endl;
for(int i = 0; i < n; i++){
if(a[i] == 1){
if(i == 0 || i == n-1) continue;
else{
ll tmp = sum - a[i-1] * a[i-1] - a[i] * a[i] - a[i+1] * a[i+1];
tmp += (a[i-1] + a[i] + a[i+1]) * (a[i-1] + a[i] + a[i+1]);
ans = max(ans,tmp);
//cout << i << ": " <<ans << endl;
}
}
}
printf("Case #%d: %lld\n",++cas,ans);
}
return 0;
}