首页 > 代码库 > zoj3690 Choosing number 矩阵

zoj3690 Choosing number 矩阵

Choosing number

Time Limit: 2 Seconds      Memory Limit: 65536 KB

There are n people standing in a row. And There are m numbers, 1.2...m. Every one should choose a number. But if two persons standing adjacent to each other choose the same number, the number shouldn‘t equal or less thank. Apart from this rule, there are no more limiting conditions.

And you need to calculate how many ways they can choose the numbers obeying the rule.

Input

There are multiple test cases. Each case contain a line, containing three integer n (2 ≤ n ≤ 108), m (2 ≤ m ≤ 30000), k(0 ≤ k ≤ m).

Output

One line for each case. The number of ways module 1000000007.

Sample Input

4 4 1

Sample Output

216




#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;
const ll mod=1000000007;

struct matrix{
    ll f[2][2];
};

matrix mul(matrix a,matrix b){
    matrix s;
    memset(s.f,0,sizeof s.f);
    ll i,j,k;
    for(i=0;i<2;i++)
        for(j=0;j<2;j++)
    for(k=0;k<2;k++){
        s.f[i][j]+=a.f[i][k]*b.f[k][j];
        s.f[i][j]%=mod;
    }
    return s;
}

matrix pow_mod(matrix a,ll k){
    matrix s;
    s.f[0][0]=s.f[1][1]=1;
    s.f[0][1]=s.f[1][0]=0;
    while(k){
        if(k&1)   s=mul(s,a);
        a=mul(a,a);
        k>>=1;
    }
    return s;
}

int main(){
    ll n,m,k;
    while(cin>>n>>m>>k){
        matrix e;
        e.f[0][0]=e.f[1][0]=m-k;
        e.f[0][1]=k;
        e.f[1][1]=k-1;


        e=pow_mod(e,n-1);
        ll ans=((m-k)*e.f[0][0]+k*e.f[1][0]+(m-k)*e.f[0][1]+k*e.f[1][1])%mod;
        cout<<ans<<endl;
    }
    return 0;
}


zoj3690 Choosing number 矩阵