问题描述:描述不准确,把英文描述贴上来
|
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;
}
}
};
循环虫群模拟
本文介绍了一个基于红绿两色虫群的循环模拟问题。通过使用0和1替代红绿虫,将问题转化为位运算的形式进行简化。代码实现包括旋转、反转操作及周期长度的计算。
514

被折叠的 条评论
为什么被折叠?



