/*题目链接*/
题意:有一串由“r”、“b”、“w”构成的环形项链,“r”代表红色,“b”代表蓝色,“w”可以代表红蓝两色。现在需要把该项链断开,问断开后断点两侧相同颜色的珠子加起来最多有多少个。“bwwwbbw”、“rrrr”都是连续颜色的珠子,断点左侧的珠子允许和右侧的珠子颜色不同。
题目分析:
因为珠子的个数最多之后350个,所以我们可以枚举断点的位置,然后分别向两侧扩展,将能扩展出的珠子数和最大值比较,更新最大值,最后输出答案。
扩展时注意点:1、向左扩展时,当位于下标0处,再扩展应该扩展下标为n-1的珠子,向右同理。(项链是环形的)
2、“w”既可以当蓝色也可以当红色,但它本身不是一种颜色,所以只需考虑红色、蓝色的情况。
AC代码:
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <climits>
#include <cassert>
#include <complex>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
int down(int i,int n)
{
return (i-1+n)%n;
}
int up(int i,int n)
{
return (i+1+n)%n;
}
bool check(int i, char ch, string &s)
{
if (ch == 'w' || s[i] == 'w')
return true;
if (s[i] != ch)
return false;
return true;
}
int main()
{
int n,ans=0;
string s;
cin >> n >> s;
for (int i=0; i<n; ++i)
{
bool a[400] = {0};
int j = down(i,n),ans1=0,ans2=0,ch = 'w';
while (!a[j])
if (j==down(i,n) || check(j,ch,s))
{
++ans1;
a[j] = true;
if (s[j] != 'w')
ch = s[j];
j = down(j,n);
}
else
break;
j = i;
ch = 'w';
while (!a[j])
if (j==i || check(j,ch,s))
{
++ans2;
a[j] = true;
if (s[j] != 'w')
ch = s[j];
j = up(j,n);
}
else
break;
ans = max(ans,ans1+ans2);
}
cout << ans << endl;
return 0;
}