hdu 2971 Tower

刚开始,一直LE,后来优化了下

Accepted 2971 3265MS 232K 1105 B C++  

 

#include<iostream>
using namespace std;
typedef
__int64 int64;
int64 x,y,a2,n,mod;
struct
matrix
{

    int64 a[4][4];
}
e,p;
matrix mul(matrix m,matrix n)
{

    matrix ans;
    for
(int i=0;i<4;i++)
        for
(int j=0;j<4;j++)
        {

            ans.a[i][j]=0;
            for
(int k=0;k<4;k++)
            {

                if
(m.a[i][k]&&n.a[k][j]) {
                    ans.a[i][j]=(ans.a[i][j]+m.a[i][k]*n.a[k][j])%mod;
                }
            }
        }

    return
ans;
}

matrix fun1(matrix m,long n)
{

    matrix ans;
    ans=e;
    while
(n)
    {

        if
(n&1)
            ans=mul(m,ans);
        n>>=1;
        m=mul(m,m);
    }

    return
ans;
}

int
main()
{

    int
i,j,t;
    for
(i=0;i<4;i++)
        for
(j=0;j<4;j++)
            e.a[i][j]=(i==j);
    scanf("%d",&t);
    while
(t--)
    {

        scanf("%I64d%I64d%I64d",&a2,&n,&mod);
        matrix ans;
        int64 sum=0;
        memset(p.a,0,sizeof(p.a));
        x=(2*a2)%mod;
        p.a[0][0]=p.a[0][1]=1;p.a[1][1]=(x*x)%mod;p.a[1][2]=1;p.a[1][3]=(mod-2*x)%mod;
        p.a[2][1]=1;p.a[3][1]=x;p.a[3][3]=mod-1;
        ans=fun1(p,n-1);
        sum=ans.a[0][0]+((ans.a[0][1]*a2)%mod*a2)%mod+ans.a[0][2]+(ans.a[0][3]*a2)%mod;
        while
(sum<0)
            sum+=mod;
        printf("%I64d\n",sum%mod);
    }

    return
0;
}

你可能感兴趣的:(HDU)