SDNU OJ -- 1493/1340 矩阵快速幂

题目链接http://www.acmicpc.sdnu.edu.cn/problem/show/1493

题意很简单,多组输入,问你(1+sqrt(2))^n = sqrt(m)+sqrt(m-1)是否成立,输出m%(1e9+7)...

开始我完全不知道这个题该怎么做,还是百度了一下,这原来是个找规律+矩阵快速幂!!

详见这位大佬的博客吧:https://blog.csdn.net/winycg/article/details/69808789(其实是我懒得打那些符号了)

AC代码:

#include
#include
#include
using namespace std;

const int MOD = 1000000007;
const int nn = 2;
typedef long long ll;
#define mod(x) ((x)%MOD)

struct mat{
	ll m[2][2];
}unit;

mat operator * (mat a, mat b){
	mat ret;
	ll x;
	for(int i = 0; i < nn; i++){
		for(int j = 0; j < nn; j++){
			x = 0;
			for(int k = 0; k < nn; k++)
				x += mod(a.m[i][k] * b.m[k][j]);
			ret.m[i][j] = mod(x);
		}
	}
	return ret;
}

void init_unit(){
	for(int i = 0; i < 2; i++){
		unit.m[i][i] = 1;
	}
}

mat pow_mat(mat a, ll n){
	mat ret = unit;
	while(n){
		if(n&1)	ret = ret*a;
		a = a*a;
		n >>= 1;
	}
	return ret;
}

int main()
{
	ll n;
	while(~scanf("%lld", &n)){
		mat a, aria;
		a.m[0][0] = a.m[1][0] = a.m[1][1] = 1;
		a.m[0][1] = 2;
		init_unit();
		aria = pow_mat(a, n-1);
		ll t = mod( (aria.m[0][0] + aria.m[0][1]) );  
        if(n&1)  
            cout << (ll)mod((t*t+1)) <

补一个:1340

#include
#include
#include
using namespace std;

typedef long long ll;
const int mod = 1000000007;
struct mat{
    ll a[2][2];
};

mat mat_mul(mat x, mat y)
{
    mat res;
    memset(res.a, 0, sizeof(res.a));
    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 2; j++){
            for(int k = 0; k < 2; k++){
                res.a[i][j] = (res.a[i][j] + x.a[i][k] * y.a[k][j]) % mod;
            }
        }
    }
    return res;
}

ll pow_matrix_mod(int n, int a, int b)
{
    mat c, res;
    memset(res.a, 0, sizeof(res.a));
    c.a[0][0] = a; c.a[0][1] = b;
    c.a[1][0] = 1; c.a[1][1] = 0;
    for(int i = 0; i < 2; i++){
        res.a[i][i] = 1;
    }
    n -= 1;
    while(n){
        if(n & 1)   res = mat_mul(res, c);
        c = mat_mul(c, c);
        n >>= 1;
    }
    cout << (res.a[1][0] + res.a[1][1]) % mod << '\n';
}

int main()
{
    int n, a, b;
    while(~scanf("%d %d %d", &a, &b, &n)){
        if(n == 0 && a == 0 && b == 0) break;
        pow_matrix_mod(n, a, b);
    }
}



你可能感兴趣的:(题目集)