There are n lights in a circle numbered from 1 to n. The left of light 1 is light n, and the left of light k (1< k<= n) is the light k-1.At time of 0, some of them turn on, and others turn off.
Change the state of light i (if it's on, turn off it; if it is not on, turn on it) at t+1 second (t >= 0), if the left of light i is on !!! Given the initiation state, please find all lights’ state after M second. (2<= n <= 100, 1<= M<= 10^8)
Input
The input contains one or more data sets. The first line of each data set is an integer m indicate the time, the second line will be a string T, only contains '0' and '1' , and its length n will not exceed 100. It means all lights in the circle from 1 to n.
If the ith character of T is '1', it means the light i is on, otherwise the light is off.
Output
For each data set, output all lights' state at m seconds in one line. It only contains character '0' and '1.
Sample Input
1 0101111 10 100000001
Sample Output
1111000 001000010
题意分析:先认真读题,题目中重要的内容都已经给我们用红色字体标出,就是提醒我们,灯的开关变换是与左边灯的状态有关的。这里我们还需要注意一点,就是灯是一个环。
读懂题目后,接下来分析我们要解决的
1.如何实现左边灯的状态与当前灯的开关联系。即如何在左边为1时让当前状态的0与1进行相互转换,对二进制稍微了解就能看出,这就是二进制的1与当前数相加。
2.如何实现连续的灯的状态的变化?这里结合1的分析,我们可以分析出这是一个递推变化的二进制数列,那么我们可以考虑通过矩阵的变化来实现,每一秒钟的变化,就是一次状态的变化,这里使用矩阵快速幂加速这种变化即可。
分析递推关系,得到状态转移矩阵 ,初始矩阵为
,通过对状态转移矩阵使用快速幂就达到了我们想要的结果。对于二进制的使用,设定模为2就可以了。
#include <iostream>
#include <cstring>
#define ll long long
using namespace std;
const ll Mod = 2;
ll N;
struct Matrix
{
int m[101][101];
};
Matrix multi(Matrix a, Matrix b)
{
Matrix ans;
memset(ans.m, 0, sizeof(ans.m));
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
for(int k = 1; k <= N; k++)
ans.m[i][j] = (ans.m[i][j] + a.m[i][k]*b.m[k][j] % Mod) % Mod;
return ans;
}
Matrix pow(Matrix a, ll n)
{
Matrix ans;
memset(ans.m, 0, sizeof(ans.m));
for(int i = 1; i <= N; i++)
ans.m[i][i] = 1;
while(n)
{
if(n&1)
ans = multi(ans, a);
n >>= 1;
a = multi(a, a);
}
return ans;
}
int main()
{
ll m;
string s;
while(cin >> m)
{
cin >> s;
N = s.size();
Matrix res, ans;
memset(res.m, 0, sizeof(res.m));
memset(ans.m, 0, sizeof(ans.m));
res.m[1][1] = 1, res.m[1][N] = 1;
for(int i =2; i <= N; i++)
{
res.m[i][i-1] = 1;
res.m[i][i] = 1;
}
for(int i = 1; i <= N; i++)
ans.m[i][1] = s[i-1] - '0';
res = pow(res, m);
ans = multi(res, ans);
for(int i = 1; i <= N; i++)
cout << ans.m[i][1];
cout << endl;
}
return 0;
}