We're clearly supposed to brute-force every possibility.
Just traverse the maximum number of beads from each possible starting point.
/*
ID: victor4
PROG: beads
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream fout ("beads.out");
ifstream fin ("beads.in");
int N;
fin >> N;
string beads;
fin >> beads;
if(beads.length() != N)
// either this or we could throw a fatal error
N = beads.length();
// brute-force all possibilities
int cur = 0, max = 0;
char color;
bool switched;
for(int i = 0; i < N; ++i){
// complexity O(n)
cur = 0;
switched = false;
color = 'w';
for(int j = 0; j < N; ++j){
// complexity O(n^2)
const char cur_c = beads[(i + j) % N];
// always take white beads
if(cur_c != 'w'){
// first non-white
if(color == 'w'){
color = cur_c;
}
else if(color != cur_c){
if(switched)
break;
else{
color = cur_c;
switched = true;
}
}
}
++cur;
}
if(cur > max)
max = cur;
}
fout << max << endl;
return 0;
}
what is the bool switched for?
ReplyDeleteThere are only two colors, so all the white beads are collected along with the same colored ones, then all of the white beads along with the other color, and the count is checked. This is done for every starting position, which really isn't needed.
DeleteWhat is "const char cur_c = beads[(i + j) % N];" for? I don't understand the modulo.
ReplyDeleteI did this a long time ago, but here is my attempt at a reply.
DeleteThe necklace wraps around. If n=5, this is a valid slice of the necklace: beads[3], beads[4], beads[0], beads[1].