题目大意:
项链最长的纯色连续段,“w”即white白色珠子,可任意涂为红或蓝,“r” “b”即红 蓝。
Input
Line 1: N, the number of beads
Line 2: a string of N characters, each of which is r, b, or w
Output
A single line containing the maximum of number of beads that can be collected from the supplied necklace.
Sample Input
29
wwwbbrwrbrbrrbrbrwrwwrbwrwrrb
Sample Output
11
DP算法
*先复制相同的一段 拼接在一起 以模拟项链的环状
#include <bits/stdc++.h> using namespace std; typedef struct node { int lr,lb,rr,rb; ///左右的red blue珠数量 }beans; int main() { beans bean[800]; char br[800],brr[400]; int n; scanf("%d%s",&n,br); strcpy(brr,br); strcat(br,brr); bean[0].lr=bean[0].lb=0; for(int i=1;i<=2*n;i++) { if(br[i-1]=='r') bean[i].lr=bean[i-1].lr+1, bean[i].lb=0; else if(br[i-1]=='b') bean[i].lb=bean[i-1].lb+1, bean[i].lr=0; else bean[i].lb=bean[i-1].lb+1, bean[i].lr=bean[i-1].lr+1; } bean[2*n].rr=bean[2*n].rb=0; for(int i=2*n-1;i>=0;i--) { if(br[i]=='r') bean[i].rr=bean[i+1].rr+1, bean[i].rb=0; else if(br[i]=='b') bean[i].rb=bean[i+1].rb+1, bean[i].rr=0; else bean[i].rb=bean[i+1].rb+1, bean[i].rr=bean[i+1].rr+1; } int m=0; for(int i=0;i<2*n;i++) m=max(m,max(bean[i].lr,bean[i].lb)+max(bean[i].rr,bean[i].rb)); if(m>n) m=n; printf("%d ",m); return 0; }