hdu 2256

Problem of Precision

     Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


Problem Description
hdu 2256_第1张图片
 

Input
The first line of input gives the number of cases, T. T test cases follow, each on a separate line. Each test case contains one positive integer n. (1 <= n <= 10^9)
 

Output
For each input case, you should output the answer in one line.
 

Sample Input
   
   
   
   
3 1 2 5
 

Sample Output
   
   
   
   
9 97 841
 

解题思路:这道题目完全没思路,看了别人的解题报告感觉还是似懂非懂。。

题目要求 (sqrt(2)+sqrt(3))的 2^n并%1024,要求出值来并不难,构造矩阵即可,但是要mod1024就有问题了,小数不能直接mod,但是如果你取整之后再mod,结果绝逼出问题,因为浮点数的精度问题。

hdu 2256_第2张图片

求出来后,直接用(int)(Xn+Yn*sqrt(6))%1024,又会出问题,还是浮点数取整问题。看来在mod的时候有浮点数要格外注意,直接处理的话,不管怎么取整,都会出问题。

所以分割线下面的推算就避开了这个问题,这个确实好难想到,通过变换一下,得到最终的结果必定是2Xn-(0.101...)^n,因为最终mod是用不大于浮点数的最大整数在mod,所以最终结果就是2Xn-1.第二条确实好难想到!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
struct Mat{
 int mat[2][2];
};
Mat E,a;
Mat operator *(Mat a,Mat b)
{
    Mat c;
    memset(c.mat,0,sizeof (Mat));
    for(int i=0;i<2;i++)
        for (int j=0;j<2;j++)
        for (int k=0;k<2;k++)
    {
        if (a.mat[i][k]>0 && b.mat[k][j]>0)
        c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
        c.mat[i][j]%=1024;
    }
    return c;
}
Mat operator ^(Mat ac,int x)
{
    Mat c;
    c=E;
    for (;x;x>>=1)
    {
        if (x&1)
            c=c*ac;
        ac=ac*ac;
    }
    return c;

}
void init()
{
    memset(E.mat,0,sizeof (Mat));
    a.mat[0][0]=5;
    a.mat[0][1]=12;
    a.mat[1][0]=2;
    a.mat[1][1]=5;
    for (int i=0;i<2;i++)
        E.mat[i][i]=1;
}
int main()
{
    init();
    int t;
    scanf("%d",&t);
    while (t--)
    {
        int n;
        scanf("%d",&n);
        Mat s=a^(n-1);
        int q1=s.mat[0][0]*5+s.mat[0][1]*2;
        int ans=(q1*2-1)%1024;
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(矩阵,递推)