zoj 2317 Nice Patterns Strike Back

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1317

简单的矩阵连乘  要用到大整数 所以用java

代码:

import java.math.BigInteger;

import java.util.Scanner;



public class Main {



	/**

	 * @param args

	 */

    public static  int M=(1<<5);

    public static int [][] ma = new int[M][M];

    public static int [][] mb = new int[M][M];

    public static int [][] mc = new int[M][M];

    

	public static void main(String[] args) {

		// TODO Auto-generated method stub

		Scanner in = new Scanner(System.in);

		int T=in.nextInt();

		while((T--)>0){

			BigInteger n;

			int m,p;

			n=in.nextBigInteger();

			m=in.nextInt();

			p=in.nextInt();

			int h=(1<<m);

			for(int i=0;i<h;++i){

				for(int j=0;j<h;++j){

					mb[i][j]=Fok(i,j,m);

				}

			}

			for(int i=0;i<h;++i){

				ma[0][i]=1;

			}

			n=n.subtract(BigInteger.ONE);

			while(n.compareTo(BigInteger.ZERO)==1){

				if(n.mod(BigInteger.ONE.add(BigInteger.ONE)).compareTo(BigInteger.ONE)==0){

					matrixMul(ma,mb,1,h,p);

				}

				n=n.divide(BigInteger.ONE.add(BigInteger.ONE));

	            matrixMul(mb,mb,h,h,p);

			}

			int ans=0;

	        for(int i=0;i<h;++i){

	        	 ans=(ans+ma[0][i])%p;

	        }

	        System.out.println(ans);

	        if(T>0){

	        	System.out.println();

	        }

		}

		

	}

	public static void matrixMul(int [][]a,int [][]b,int n,int m,int p){

		for(int i=0;i<n;++i)

		    for(int j=0;j<m;++j){

		        int tmp=0;

		        for(int l=0;l<m;++l){

		        	tmp=(tmp+a[i][l]*b[l][j])%p;

		        }

		        mc[i][j]=tmp;

		    }

		    for(int i=0;i<n;++i)

		    for(int j=0;j<m;++j)

		    a[i][j]=mc[i][j];

	}

	public static int Fok(int l,int r,int m)

	{

	    int []a=new int[10];

	    int []b=new int[10];

	    int k=0;

	    while(l>0){

	        a[k++]=(l&1);

	        l=l>>1;

	    }

	    k=0;

	    while(r>0){

	        b[k++]=(r&1);

	        r=r>>1;

	    }

	    for(int i=1;i<m;++i){

	        if(a[i]==0&&b[i]==0&&a[i-1]==0&&b[i-1]==0)

	        return 0;

	        if(a[i]==1&&b[i]==1&&a[i-1]==1&&b[i-1]==1)

	        return 0;

	    }

	    return 1;

	}



}

  

你可能感兴趣的:(Pattern)