Uva 11551 - Experienced Endeavour ( 矩阵快速幂 )

 

Uva 11551 - Experienced Endeavour ( 矩阵快速幂 )

 

Uva 11551 - Experienced Endeavour ( 矩阵快速幂 )_第1张图片

 

 

 

#include <cstdio>    
#include <cstring>
#include <algorithm>
using namespace std;
#define MAX_SIZE 50
#define MOD 1000
#define CLR( a, b ) memset( a, b, sizeof(a) )
struct Mat
{
    int n;
    int mat[MAX_SIZE][MAX_SIZE];
    Mat( int _n )
    {
        n = _n;
        CLR( mat, 0 );
    }
    void init()
    {
        for( int i = 0; i < n; ++i )
            for( int j = 0; j < n; ++j )
                mat[i][j] = ( i == j );
    }
    Mat operator * ( const Mat &b ) const
    {
        Mat c( b.n );
        for( int k = 0; k < n; ++k )
            for( int i = 0; i < n; ++i )    if( mat[i][k] )
                for( int j = 0; j < n; ++j )
                    c.mat[i][j] = ( c.mat[i][j] + mat[i][k] * b.mat[k][j] ) % MOD;
        return c;
    }
};

Mat fast_mod( Mat a, int b )
{
    Mat res( a.n );
    res.init();
    while( b )
    {
        if( b & 1 )    res = res * a;
        a = a * a;
        b >>= 1; 
    }
    return res;
}

void scan( int &x )
{
    char c;
    while( c = getchar(), c < '0' || c > '9' );
    x = c - '0';
    while( c = getchar(), c >= '0' && c <= '9' ) x = x *10 + c - '0';
}

void Orz()
{
    int n, k, t, x, y;
    scanf( "%d", &t );
    while( t-- )
    {
        scan( n ), scan( k );
        Mat c( n );
        for( int i = 0; i < n; ++i )
            scan( c.mat[i][0] );
        Mat d( n );
        for( int i = 0; i < n; ++i )
        {
            scan( x );
            for( int j = 0; j < x; ++j )
            {
                scan( y );
                d.mat[i][y] = 1;
            }
        }
        Mat res = fast_mod( d, k );
        res = res * c;
        for( int i = 0 ; i < n; ++i )
        {
            if( i != 0 ) putchar( ' ' );
            printf( "%d",res.mat[i][0] );
        }
        putchar( '\n' );
    }    
}

int main()
{
    Orz();
    return 0;    
}
代码君

 

你可能感兴趣的:(exp)