Toy Code Plant

The quick brown fox jumps over the lazy dog.

Problem 99 Broken Necklace

这个题目是标准的complete search,350的长度,即使一个个数过去代价也是很小的。完全不必考虑任何优化。analysis的方法和我差不多,但写的非常elegant,很优雅地处理了向前向后的方向问题(用了一个额外的mod函数),以及全白项链的问题。当初完全没想到整个项链都是白色的话怎么办,致使我的方法会陷入一个infinite loop。考虑问题不全面啊

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int findforward(vector<char>, int, int);
int findbackward(vector<char>, int, int);

int main(){
 int n,         // number of beads
     maxlength; // biggest number of beads can be accumulated
    
 vector<char> necklace;
 
 // get total bead number
 ifstream fin("beads.in");
 fin>>n;

 // get every bead
 for(int i = 0; i < n; ++i){
  char bead;
  fin>>bead;
     necklace.push_back(bead);
 }

 maxlength = 2;
 for(int i = 0; i < n; ++i){
  int mylength = findforward(necklace,i,n) +
                 findbackward(necklace,i-1,n);
  
  // update maxlength.              
  if(mylength > maxlength) maxlength = mylength;
  if(maxlength > n){
   maxlength = n;
   break;
  }
 }
 
 ofstream fout("beads.out");
 fout<<maxlength<<endl;
}

int findforward(vector<char> necklace, int pos, int size){
 char currbead = necklace[pos];
 char beadtype = currbead;
 int length = 1;
 int i = (pos + 1) % size; 

 if(currbead == 'w'){  // count from white bead, jump to first non-white one
     while(necklace[i] == 'w'){
      length++;
      i = (i + 1) % size;
      if(length == size) return length;
     }
     beadtype = necklace[i]; 
 }
 
 while((necklace[i] == currbead) ||
       (necklace[i] == 'w')      ||
       (necklace[i] == beadtype)){
  length++;
  i = (i + 1) % size;
  if(length == size) break;
 }
 return length;
}
int findbackward(vector<char> necklace, int pos, int size){
 char currbead,  // start point's color
      beadtype;  // actually counted color
 int length = 1;
 int i;
 
 if(pos < 0){         // count from last bead
  currbead = necklace[size - 1];
  i = size - 2;
 }else if(pos == 0){  // count from first bead
  currbead = necklace[pos];
  i = size - 1;
 }else {              // normal
  currbead = necklace[pos];
  i = pos - 1;
 }
 
 if(currbead == 'w'){  // count from white bead, jump to first non-white one
     while(necklace[i] == 'w'){
      length++;
      i--;
      if(i < 0) i = size - 1;
      if(length == size) return length;
     }
     beadtype = necklace[i]; 
 }else
     beadtype = currbead;  // normal

 while((necklace[i] == currbead) ||
       (necklace[i] == 'w')      ||
       (necklace[i] == beadtype)){
  length++;
  i--;
  if(i < 0) i = size - 1;
  if(length == size) break;
 }
 return length;
}

现在回过来再看这个问题,如果C++可以处理正则表达式的话,其实这个问题只是在一个循环数组里搜寻一个wr,wb,或者w组成最长子串。当然,如果这样的话,未免有cheat的嫌疑,毕竟Rob是希望你自己处理算法,而不是用现成的函数吧(java好像有自带的regex库?那这个问题就不是问题啦)

阅读更多
个人分类: Algorithm in USACO
想对作者说点什么? 我来说一句

Broken Necklace(参考解析)

2012年10月10日 1KB 下载

没有更多推荐了,返回首页

不良信息举报

Problem 99 Broken Necklace

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭