题意:给出N个灯,“1”表示开,“0”表示关,并且灯连成环,比如“0101”第一个“0”灯左侧是最后一个“1”,一次操作:灯i左侧若是“1”,则灯i改变状态,否则不改变,问经过k(1<=k<=10^8)次操作,每个灯的状态。
思路:矩阵相乘,推出递推矩阵即可。比如 1 0 1,操作一次是0 1 1,可以推出矩阵
1 1 0
0 1 1
1 0 1,即单位矩阵基础上每上一位是1,因为是环,左下角是1。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2276
View Code
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <string> 5 #include <algorithm> 6 #include <iostream> 7 using namespace std; 8 const int N=110; 9 10 typedef struct Matrix{ 11 int m[N][N]; 12 }Matrix; 13 Matrix init,F,unit; 14 string str; 15 int k,n; 16 17 void Init(){ 18 int cnt=0,i,j; 19 for(i=0;i<n;i++) F.m[1][i+1]=str[i]-'0'; 20 for(i=1;i<=n;i++) 21 for(j=1;j<=n;j++){ 22 if(i==j||j-i==1) init.m[i][j]=1; 23 else init.m[i][j]=0; 24 unit.m[i][j]=(i==j); 25 } 26 init.m[n][1]=1; 27 } 28 29 Matrix Mul(Matrix a,Matrix b){ 30 Matrix c; 31 for(int i=1;i<=n;i++) 32 for(int j=1;j<=n;j++){ 33 c.m[i][j]=0; 34 for(int k=1;k<=n;k++) 35 c.m[i][j]+=a.m[i][k]*b.m[k][j]; 36 c.m[i][j]%=2; //写在for循环里面就超时了...... 37 } 38 return c; 39 } 40 41 Matrix Pow(Matrix a,Matrix b){ 42 while(k){ 43 if(k&1) b=Mul(a,b); 44 a=Mul(a,a); 45 k>>=1; 46 } 47 return b; 48 } 49 50 int main(){ 51 52 // freopen("data.in","r",stdin); 53 // freopen("data.out","w",stdout); 54 55 while(scanf("%d",&k)!=EOF){ 56 cin>>str; 57 n=str.length(); 58 Init(); 59 Matrix x=Pow(init,unit); 60 x=Mul(F,x); 61 for(int i=1;i<=n;i++) printf("%d",x.m[1][i]); 62 puts(""); 63 } 64 return 0; 65 }