BZOJ-1898: [Zjoi2004]Swamp 沼泽鳄鱼(矩阵快速幂)

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1898

矩阵快速幂随便搞一搞就行了。

代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
 
using namespace std ;
 
#define mod 10000
#define MAXN 55
 
struct mat {
     
    int n , m , a[ MAXN ][ MAXN ] ;
     
    mat(  ) {
        memset( a , 0 , sizeof( a ) ) ;
        n = m = 0 ;
    }
     
    void Init_I( int _n ) {
        n = m = _n ;
        for ( int i = 0 ; i < n ; ++ i ) a[ i ][ i ] = 1 ;
    }
     
} Map[ 12 ] , temp , ans ;
 
mat operator * ( const mat &x , const mat &y ) {
    mat ret ; 
    ret.n = x.n , ret.m = y.m ;
    for ( int i = 0 ; i < ret.n ; ++ i ) {
        for ( int j = 0 ; j < ret.m ; ++ j ) {
            for ( int k = 0 ; k < x.m ; ++ k ) {
                ( ret.a[ i ][ j ] += x.a[ i ][ k ] * y.a[ k ][ j ] ) %= mod ;
            }
        }
    }
    return ret ;
}
 
mat Pow( const mat &x , int cnt ) {
    mat rec , ret = x ;
    rec.Init_I( x.n ) ;
    for ( ; cnt ; cnt >>= 1 ) {
        if ( cnt & 1 ) rec = rec * ret ;
        ret = ret * ret ;
    }
    return rec ;
}
 
int n , m , S , T , k , nf , w[ 4 ] ;
 
int main(  ) {
    scanf( "%d%d%d%d%d" , &n , &m , &S , &T , &k ) ;
    Map[ 0 ].n = Map[ 0 ].m = n ;
    while ( m -- ) {
        int s , t ; scanf( "%d%d" , &s , &t ) ;
        Map[ 0 ].a[ s ][ t ] = Map[ 0 ].a[ t ][ s ] = 1 ;
    }
    for ( int i = 1 ; i < 12 ; ++ i ) Map[ i ] = Map[ i - 1 ] ;
    scanf( "%d" , &nf ) ;
    while ( nf -- ) {
        int t ; scanf( "%d" , &t ) ;
        for ( int i = 0 ; i < t ; ++ i ) scanf( "%d" , &w[ i ] ) ;
        for ( int i = 0 ; i < 12 ; ++ i ) {
            int x = w[ i % t ] ;
            if ( i ) {
                for ( int j = 0 ; j < n ; ++ j ) Map[ i - 1 ].a[ j ][ x ] = 0 ;
            }
            for ( int j = 0 ; j < n ; ++ j ) Map[ i ].a[ x ][ j ] = 0 ;
        }
    }
    temp.Init_I( n ) ;
    ans.Init_I( n ) ;
    for ( int i = 0 ; i < 12 ; ++ i ) temp = temp * Map[ i ] ;
    ans = ans * Pow( temp , k / 12 ) ;
    for ( int i = 0 ; i < k % 12 ; ++ i ) ans = ans * Map[ i ] ;
    printf( "%d\n" , ans.a[ S ][ T ] ) ;
    return 0 ; 
}
    原文作者:AmadeusChan
    原文地址: https://www.jianshu.com/p/c1ae14a75607
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞