[topCoder-每日一二题]--[3]

来源:互联网 发布:mac lol美服转日服 编辑:程序博客网 时间:2024/05/16 08:24

问题描述:描述不准确,把英文描述贴上来

A group of social bugs lives in a circular formation. These bugs are either red or green. Once every minute, a new green bug appears between each pair of adjacent bugs of different colors, and a new red bug appears between each pair of adjacent bugs of the same color. After that, all the original bugs die and the process is repeated. It is known that every initial formation of bugs will always lead to a cycle. The cycle length of the formation is defined as the amount of time between any of its two identical formations. Two formations are considered identical if one formation can be achieved by rotating and/or reversing the other one. For example via rotation, "RRGG" is identical to "RGGR", but it is NOT identical to "RGRG". Via reversal, "RRGGRG" is identical to "GRGGRR" and now via rotation it is also identical to "RRGRGG".

Given a String formation of bugs on a circle return the length of the cycle for that formation. Each character in formation will be either 'R' or 'G' representing the red and green bugs respectively. The formation is circular, so the bug represented by the first character is adjacent to the bug represented by the last character in formation.

解决:

使用01来代替RG,使得问题转化并且简化,>> << | & 运算小  

代码:

#include <set>
#include <algorithm>
#include <string>
#include <iostream>
#include <map>
#include <iterator>
using namespace std;
class CircleBugs
{
private:
 int rotate(int val,int n)
 {
  return (val>>1)|((val&1)<<(n-1));
 }
public: 
 int cycleLength(string form)
 {
 int bug = 0;
 map<int,int>bugmap;
 int len =form.size();
 for(int i = 0; i < len; i++)
  if(form[i]=='G')
   bug|=(1<<i);
 for(int ci=0;;ci++)
 {
  bug=bug^rotate(bug,len);
  for(int i = 0; i < len; i++)
  {
   map<int,int>::iterator iter=bugmap.find(bug);
   if(iter!=bugmap.end())
    return ci-(*iter).second;
   cout<<bug<<endl;
   bug=rotate(bug,len);
   
  }
  
  bugmap[bug]=ci;
  
 }
 }
};

原创粉丝点击