BNU Choosing number 矩阵快速幂

来源:互联网 发布:水果合成软件下载 编辑:程序博客网 时间:2024/06/03 14:57

                                                                     Choosing number

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 than k. 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


Source
ZOJ Monthly, March 2013


刚开始想直接YY,后面一直卡一些数据,WA到死,后面看人家写的,竟然是用到矩阵的思想。。。

题意:给出n个人,选m个数,当两个人选择相同的数时,这两个数必须是大于k的,问满足这个条件有几种方案

思路:设Max[i]代表上第i个人选了大于k的方案数,Min[i]代表第i个人选了小于等于k的方案数

有 Max[i] = Max[i-1]*(m-k) + Min[i-1]*(m-k);

     Min[i] = Max[i-1] *k+ Min[i-1]*(k-1);


代码:

#include <iostream>#include <stdio.h>#include <cstring>#include <cmath>#include <algorithm>using namespace std;#define mod 1000000007const int M=100005;long long n,m,k;struct mat{    int m[2][2];};mat mul(mat a,mat b){    mat c;    memset(c.m,0,sizeof(c.m));    for(int i=0 ; i<2; i++)        for(int j=0 ; j<2; j++)            for(int k=0 ; k<2 ; k++)                c.m[i][j] = (c.m[i][j]+a.m[i][k]*b.m[k][j])%mod;    return c;}mat ksmff(mat a,long long  b){    mat ret;    ret.m[0][0]=ret.m[1][1]=1;    ret.m[0][1]=ret.m[1][0]=0;    while(b)    {        if(b&1)        ret = mul(ret,a);        a=mul(a,a);        b=b>>1;    }    return ret;}mat ans;long long sum;int main(){    while(scanf("%d%d%d",&n,&m,&k)!=EOF)    {        ans.m[0][0]=m-k;        ans.m[0][1]=k;        ans.m[1][0]=m-k;        ans.m[1][1]=k-1;        ans = ksmff(ans,n-1);//这个矩阵的n-1次方        sum = (ans.m[0][0]*(m-k)+ ans.m[1][0]*k + ans.m[0][1] *(m-k)+ans.m[1][1]*k)%mod;        printf("%lld\n",sum);    }    return 0;}