Lucky Coins Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 827 Accepted Submission(s): 432
Problem Description
As we all know,every coin has two sides,with one side facing up and another side facing down.Now,We consider two coins's state is same if they both facing up or down.If we have N coins and put them in a line,all of us know that it will be 2^N different ways.We call a "N coins sequence" as a Lucky Coins Sequence only if there exists more than two continuous coins's state are same.How many different Lucky Coins Sequences exist?
Input
There will be sevaral test cases.For each test case,the first line is only a positive integer n,which means n coins put in a line.Also,n not exceed 10^9.
Output
You should output the ways of lucky coins sequences exist with n coins ,but the answer will be very large,so you just output the answer module 10007.
Sample Input
3 4
Sample Output
2 6题意:n枚硬币,正反2面,排列共有2^n中可能,求至少有3种同面相连的情况。解析:即求2^n-最多有2种相连的情况。(以下是网上搜的详细解释)设 f(n) 为长度是 n 的不包含连续 3 个或以上相同的 1 或 0 的 01 串 ,
则 f(1)=2,f(2)=4,f(3)=6,f(4)=10
当 n>4 的时候 , 分情况考虑 :
1、 如果是以 00 或者 11 结尾 , 则分别有 f(n-2)/2 种情况 , 加起来就是 f(n-2) 种 .
2、 如果是以 01 或者 10 结尾 , 则第 n 个字符要和第 n-1 个字符不一样 , 那么分别有 f(n-1)/2 种 , 加起来就是 f(n-1)
则统计起来就是 f(n)=f(n-1)+f(n-2), 题目要求的是包含连续三个相同的 0 或 1 串的串数 , 那就是用 a[n]=(2^n-f(n))%10007.
然而这样还不好求 , 先不看 %10007, 转换成递推公式是 a[n]=a[n-1]+a[n-2]+2^(n-2),
转换成矩阵 :
a[n] 1 1 1 a[n-1]
a[n-1] = 1 0 0 * a[n-2]
2^(n-1) 0 0 2 2^(n-2)
这样就可以用矩阵幂快速算出 a[n], 复杂度为 O(logn)
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; void mult(int a[4][4],int b[4][4]) { int c[4][4]; memset(c,0,sizeof(c)); for(int i=1;i<=3;i++) for(int j=1;j<=3;j++) for(int k=1;k<=3;k++) c[i][j]+=a[i][k]*b[k][j]%10007; memcpy(a,c,sizeof(c)); } int main() { int n,i,j; int m[4][4],res[4][4]; int a[5]={0,0,0,2,6}; while(cin>>n) { if(n<4) { cout<<a[n]<<endl; continue; } m[1][1]=m[1][2]=m[1][3]=m[2][1]=1; m[2][2]=m[2][3]=m[3][1]=m[3][2]=0; m[3][3]=2; for(i=1;i<=3;i++) for(j=1;j<=3;j++) if(i==j)res[i][j]=1;else res[i][j]=0; n-=4; while(n) { if(n&1){mult(res,m);n--;} else { mult(m,m); n>>=1; } } int k=(res[1][1]*6+res[1][2]*2+res[1][3]*8)%10007; cout<<k<<endl; } }