HDU 2276 Kiki & Little Kiki 2

矩阵快速幂。

0 1-> 第二个数字会变成1

0 0-> 第二个数字会变成0

1 0-> 第二个数字会变成1

1 1-> 第二个数字会变成0

根据这四个特点,就可以写转移矩阵了。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-6;
void File()
{
    freopen("D:\\in.txt","r",stdin);
    freopen("D:\\out.txt","w",stdout);
}
template <class T>
inline void read(T &x)
{
    char c = getchar();
    x = 0;
    while(!isdigit(c)) c = getchar();
    while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); }
}

char s[105];
int len,m;

struct Matrix
{
    int A[105][105];
    int R, C;
    Matrix operator*(Matrix b);
};

Matrix X, Y, Z;

Matrix ch(Matrix a, Matrix b)
{
    Matrix c;
    memset(c.A, 0, sizeof(c.A));
    int i, j, kk;
    for (i = 1; i <= len; i++)
        for (j = 1; j <= len; j++)
        {
            if(a.A[i][j])
            {
                for (kk = 1; kk <= len; kk++)
                    c.A[i][kk] = (c.A[i][kk]+a.A[i][j] * b.A[j][kk])%2;

            }
        }
    return c;
}

void init()
{
    for(int i=1;i<=len;i++) Z.A[1][i] = s[i-1]-'0';
    Z.R = 1; Z.C = len;

    memset(Y.A,0,sizeof Y.A);
    for(int i=1;i<=len;i++) Y.A[i][i]=1;
    Y.R = len; Y.C = len;

    memset(X.A,0,sizeof X.A);
    X.A[1][1]=1; X.A[len][1]=1;
    for(int i=2;i<=len;i++) X.A[i][i]=1, X.A[i-1][i]=1;

    X.R = len; X.C = len;
}

void work()
{
    while (m)
    {
        if (m % 2 == 1) Y = ch(Y,X);
        m = m >> 1;
        X = ch(X,X);
    }
    Z = ch(Z,Y);

    for(int i=1;i<=len;i++) printf("%d",Z.A[1][i]);
    printf("\n");
}

int main()
{
    while(~scanf("%d%s",&m,s))
    {
        len=strlen(s);
        init();
        work();
    }

    return 0;
}

 

posted @ 2017-01-17 18:42  Fighting_Heart  阅读(119)  评论(0编辑  收藏  举报