BNU Choosing number 矩阵快速幂

                                                                     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 1000000007
const 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值