USACO 1.1 Broken Necklace

Brutal force O(N^2) solution.


#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main ()
{
string str;
int n, i, l, r, mx = 0;
ifstream fin ("beads.in");
ofstream fout ("beads.out");
fin >> n;
fin >> str;
str += str;
for (i = 0; i < n; i++) {
l = r = 1;
int k = i + 1;
char flag;
while(l < n) {
int j = i;
while(str[j] == 'w')
j++;
flag = str[j];
if (str[k] == flag || str[k] == 'w')
k++, l++;
else break;
}

k = i + n - 2;
while(r < n) {
int j = i;
while(str[j] == 'w')
j--;
if (str[k] == str[i + n - 1] || str[k] == 'w')
k--, r++;
else break;
}

if (l + r > mx) mx = l + r;
}

if (mx > n) mx = n;
fout << mx << endl;
return 0;
}