1. 程式人生 > >HDU 5583 - Kingdom of Black and White題解

HDU 5583 - Kingdom of Black and White題解

輸入 代碼 long long stack div 通知 ems pre gist

此文為博主原創題解,轉載時請通知博主,並把原文鏈接放在正文醒目位置。

題目鏈接(vjudge):https://vjudge.net/problem/HDU-5583

題目大意:

輸入第一行為一個數字T,表示數據組數(1<=T<=50)。

接下來每一行有一個長度不超過100000的字符串,由0/1組成。

你可以對這個字符串進行一次操作,選擇把一個0變成1或者把一個1變成0(也可以不操作).

之後,這個字符串的值就等於字符串中相鄰相同的字符串長度的平方和。我們想令這個值最大。

例如000011,選擇把第一個1變成0,即000001,字符串的值就是5*5+1*1=26.

輸出最大值。

Sample Input
2
000011
0101
Sample Output
Case #1: 26
Case #2: 10

分析:

大概就是個模擬,先處理出每個連續串的長度,再枚舉修改哪一個數字。

註意參與運算的變量全部要開long long

AC代碼:

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<queue>
 6 #include<stack>
 7 
 8 inline int
Min(int a,int b) 9 {return a<b?a:b;} 10 11 inline long long Max(long long a,long long b) 12 {return a>b?a:b;} 13 14 int t,n,tmp,tot; 15 long long note[100002],ans,mx; 16 char s[100005]; 17 18 void init() 19 { 20 tmp = 1,tot = 0; 21 mx = 0,ans = 0; 22 memset(note,0,sizeof(note));
23 } 24 25 int main() 26 { 27 // freopen("1.txt","r",stdin); 28 // freopen("stone.in","r",stdin); 29 // freopen("stone.out","w",stdout); 30 scanf("%d",&t); 31 for(int x = 1;x <= t;++ x) 32 { 33 init(); 34 scanf("%s",s); 35 n = strlen(s); 36 for(register int i = 1;i < n;++ i){ 37 if(s[i] == s[i-1]) 38 ++ tmp; 39 else{ 40 note[++ tot] = 1LL*tmp; 41 mx += 1LL*tmp*tmp; 42 tmp = 1; 43 } 44 } 45 note[++ tot] = 1LL*tmp; 46 mx += 1LL*tmp*tmp; 47 ans = mx; 48 for(int i = 1;i < tot;++ i) 49 { 50 if(note[i+1] == 1) 51 ans = Max(ans,1LL*(mx-note[i]*note[i]-note[i+1]*note[i+1]-note[i+2]*note[i+2]+(note[i]+note[i+1]+note[i+2])*(note[i]+note[i+1]+note[i+2]))); 52 else 53 ans = Max(ans,1LL*(mx-note[i]*note[i]-note[i+1]*note[i+1]+(note[i+1]-1)*(note[i+1]-1)+(note[i]+1)*(note[i]+1))); 54 if(note[i] == 1) 55 ans = Max(ans,1LL*(mx-note[i]*note[i]-note[i+1]*note[i+1]-note[i-1]*note[i-1]+(note[i-1]+note[i]+note[i+1])*(note[i-1]+note[i]+note[i+1]))); 56 else 57 ans = Max(ans,1LL*(mx-note[i]*note[i]-note[i+1]*note[i+1]+(note[i]-1)*(note[i]-1)+(note[i+1]+1)*(note[i+1]+1))); 58 } 59 printf("Case #%d: %I64d\n",x,ans); 60 } 61 return 0; 62 }

HDU 5583 - Kingdom of Black and White題解