Classic matrix Question 7: Warcraft III daemon (recursive matrix acceleration)

Source: Internet
Author: User
Tags mul

Https://www.vijos.org/p/1067


It is easy to introduce the recursive formula F [N] = f [n-1] + F [N-2] +... + F [n-k].

Methods of constructing a matrix: To construct a K * k matrix, where the upper right corner of the (k-1) * (k-1) matrix is the unit matrix, each number in the k-th row corresponds to the coefficients of F [n-1], F [N-2], and f [n-k] respectively. Then, a K * 1 matrix is constructed. Its line I represents f [I], which is obtained through direct recursion. Set ans [] [] to the n-k power of the first matrix to multiply the second matrix. f [N] Is ans [k] [1].


Note: Use _ int64


#include <stdio.h>#include <iostream>#include <map>#include <set>#include <list>#include <stack>#include <vector>#include <math.h>#include <string.h>#include <queue>#include <string>#include <stdlib.h>#include <algorithm>#define LL long long#define _LL __int64#define eps 1e-12#define PI acos(-1.0)#define C 240#define S 20using namespace std;const int maxn = 15;const int mod = 7777777;int k;struct matrix{_LL mat[maxn][maxn];void init(){memset(mat,0,sizeof(mat));for(int i = 1; i <= maxn; i++)mat[i][i] = 1;}}a,b;matrix mul(matrix a, matrix b){matrix ans;memset(ans.mat,0,sizeof(ans.mat));for(int i = 1; i <= k; i++){for(int g = 1; g <= k; g++){if(a.mat[i][g] == 0) continue;for(int j = 1; j <= k; j++){ans.mat[i][j] = (ans.mat[i][j] + a.mat[i][g] * b.mat[g][j])%mod;}}}return ans;}matrix pow(matrix a, int n){matrix ans;ans.init();while(n){if(n&1)ans = mul(ans,a);a = mul(a,a);n >>= 1;}return ans;}int main(){int n;while(~scanf("%d %d",&k,&n)){memset(a.mat,0,sizeof(a.mat));for(int i = 1; i <= k-1; i++)a.mat[i][i+1] = 1;for(int i = 1; i <= k; i++)a.mat[k][i] = 1;matrix ans = pow(a,n-k);memset(b.mat,0,sizeof(b.mat));b.mat[0][1] = 1;for(int i = 1; i <= k; i++){for(int j = 0; j < i; j++)b.mat[i][1] += b.mat[j][1];}ans = mul(ans,b);printf("%I64d\n",ans.mat[k][1]);}return 0;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.