Kiki & Little Kiki 2
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
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
Sample Output
解题思路:问题是给一排灯的开关状态,如果左边的灯前一秒是亮着的,那么该灯下一秒就变换状态,否则不变。问m秒后的情况。显然,第i盏灯在某一秒的状态ai,在下一秒时状态应该为(ai+ai-1)% 2,其实就是与左边进行异或运算。那么这道题目就很好利用状态矩阵来算了,构造好矩阵在m次方即可。。
这道题目在hdu上可以A,但在nyoj上就超时了
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
const int mod = 2;
struct Matrix
{
int m[100][100];
};
Matrix I,base;
int v[100],n;
char str[100];
void init()
{
for(int i = 0; i < 100; i++)
I.m[i][i] = 1;
}
Matrix mul(Matrix a,Matrix b)
{
Matrix c;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
c.m[i][j] = 0;
for(int k = 0; k < n; k++)
{
c.m[i][j] = (c.m[i][j] + a.m[i][k]*b.m[k][j]) % mod;
}
}
return c;
}
Matrix power(Matrix A,int k)
{
Matrix ans = I;
while(k)
{
if(k & 1) ans = mul(ans,A);
A = mul(A,A);
k >>= 1;
}
return ans;
}
void build_matrix() //构建n*n的矩阵
{
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
if(i == 0)
{
if(j == 0 || j == n-1)
base.m[i][j] = 1;
else base.m[i][j] = 0;
}
else
{
if(j == i-1 || j == i)
base.m[i][j] = 1;
else base.m[i][j] = 0;
}
}
}
int main()
{
init();
LL m;
while(scanf("%I64d",&m)!=EOF)
{
getchar();
gets(str);
n = strlen(str);
build_matrix();
for(int i = 0; i < n; i++)
v[i] = str[i] - '0';
Matrix A = power(base,m);
int ans[100];
for(int i = 0; i < n; i++)
{
ans[i] = 0;
for(int k = 0; k < n; k++)
{
ans[i] = (ans[i] + A.m[i][k]*v[k]) % mod;
}
}
for(int i = 0; i < n; i++)
printf("%d",ans[i]);
printf("\n");
}
return 0;
}