zoukankan      html  css  js  c++  java
  • count(矩阵快速幂)

    Problem Description

    Farmer John有n头奶牛.
    某天奶牛想要数一数有多少头奶牛,以一种特殊的方式:
    第一头奶牛为1号,第二头奶牛为2号,第三头奶牛之后,假如当前奶牛是第n头,那么他的编号就是2倍的第n-2头奶牛的编号加上第n-1头奶牛的编号再加上自己当前的n的三次方为自己的编号.
    现在Farmer John想知道,第n头奶牛的编号是多少,估计答案会很大,你只要输出答案对于123456789取模.

    Input

    第一行输入一个T,表示有T组样例
    接下来T行,每行有一个正整数n,表示有n头奶牛 (n>=3)
    其中,T=10^4,n<=10^18

    Output

    共T行,每行一个正整数表示所求的答案

    Sample Input

    
     

    5 3 6 9 12 15

    Sample Output

    
     

    31 700 7486 64651 527023

    Source

    “字节跳动-文远知行杯”广东工业大学第十四届程序设计竞赛

    ps:矩阵快速幂:https://blog.csdn.net/wust_zzwh/article/details/52058209

    #include <iostream>
    #include <bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    #define mod 123456789
    #define maxn 6
    struct mat{
        ll a[maxn][maxn];
        mat operator*(const mat b){
            mat temp;
            memset(temp.a,0,sizeof(temp.a));
            int i,j,k;
            for(i=0;i<maxn;i++){
                for(j=0;j<maxn;j++){
                    for(k=0;k<maxn;k++){
                        temp.a[i][j]=(temp.a[i][j]+a[i][k]*b.a[k][j]%mod)%mod;
                    }
                }
            }
            return temp;
        }
    };
    ll matpow(ll n){
        if(n<3) return n;
        else n-=2;
        mat c={
        1,2,1,3,3,1,
        1,0,0,0,0,0,
        0,0,1,3,3,1,
        0,0,0,1,2,1,
        0,0,0,0,1,1,
        0,0,0,0,0,1
        },res={
        1,0,0,0,0,0,
        0,1,0,0,0,0,
        0,0,1,0,0,0,
        0,0,0,1,0,0,
        0,0,0,0,1,0,
        0,0,0,0,0,1
        };
        while(n){
            if(n&1) res=res*c;
            c=c*c;
            n>>=1;
        }
        res=res*mat{
            2,0,0,0,0,0,
            1,0,0,0,0,0,
            8,0,0,0,0,0,
            4,0,0,0,0,0,
            2,0,0,0,0,0,
            1,0,0,0,0,0
        };
        return res.a[0][0]%mod;
    }
    int main()
    {
        ll n,t;
        cin>>t;
        while(t--){
            scanf("%lld",&n);
            printf("%lld
    ",matpow(n));
        }
        return 0;
    }
    
  • 相关阅读:
    POST和GET的区别
    Java设计模式6大原则
    JAVA23种工厂模式
    使用jsp实现用户登录请求
    MVC模式
    使用idea查询数据库内容
    mysql常见错误
    定义外键和建表原则
    CSS制作圆角边框
    2、JS的编写位置
  • 原文地址:https://www.cnblogs.com/skyleafcoder/p/12319520.html
Copyright © 2011-2022 走看看