Monday, April 2, 2012

Problem 99: Broken Necklace

First attempt! w00t! For the last Section 1.1 too!

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;
}

4 comments:

  1. what is the bool switched for?

    ReplyDelete
    Replies
    1. There 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.

      Delete
  2. What is "const char cur_c = beads[(i + j) % N];" for? I don't understand the modulo.

    ReplyDelete
    Replies
    1. I did this a long time ago, but here is my attempt at a reply.

      The necklace wraps around. If n=5, this is a valid slice of the necklace: beads[3], beads[4], beads[0], beads[1].

      Delete