Kingdom of Black and WhiteTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 93 Accepted Submission(s): 41
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
Sample Output
Source
|
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<iostream>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre(){freopen("c://test//input.in","r",stdin);freopen("c://test//output.out","w",stdout);}
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1,class T2>inline void gmax(T1 &a,T2 b){if(b>a)a=b;}
template <class T1,class T2>inline void gmin(T1 &a,T2 b){if(b<a)a=b;}
const int N=1e5+10,M=0,Z=1e9+7,ms63=1061109567;
int casenum,casei;
char s[N];
int bl[N];
int num[N];
LL K(LL x){return x*x;}
int main()
{
scanf("%d",&casenum);
for(casei=1;casei<=casenum;++casei)
{
scanf("%s",s+1);
int n=strlen(s+1);s[0]=s[n+1]=0;
MS(num,0);
int id=1;
LL sum=0;
for(int i=1;i<=n;++i)
{
bl[i]=id;
++num[id];
if(s[i]!=s[i+1]){sum+=K(num[id]);++id;}
}
LL ans=sum;
for(int i=1;i<=n;++i)
{
if(s[i]!=s[i-1]||s[i]!=s[i+1])
{
LL tmp=sum-K(num[bl[i]])+K(num[bl[i]]-1);
LL len=1;
if(s[i+1]!=s[i])
{
int o=bl[i+1];
tmp-=K(num[o]);
len+=num[o];
}
if(s[i-1]!=s[i])
{
int o=bl[i-1];
tmp-=K(num[o]);
len+=num[o];
}
gmax(ans,tmp+K(len));
}
}
printf("Case #%d: %lld\n",casei,ans);
}
return 0;
}
/*
【题意】
给你一个长度为n(1e5)的01串,
对于一段长度为len的连续的0或者1,对权值的贡献是len^2
我们现在可以改变最多一个位置的数(变0为1或者变1为0)
问你可以得到的最大权值为多少,并输出。
【类型】
暴力
【分析】
这题显然必然要O(n)的时间复杂度算法。
对题这题的答案,显然可能不改变位置。于是,我们自然必要先求出初始答案。
然后,我们会枚举每个位置的数。显然,我们不会改变一段数中间的数,这只会使得答案变小。
而我们改变一个数,可能会使得左右两段数合并,就改变一下权值更新答案即可。
【时间复杂度&&优化】
O(Tn)
*/