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

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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值