zoukankan      html  css  js  c++  java
  • ZOJ 3690 Choosing number(dp矩阵优化)

    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 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
    


    题意:有n个人,1到m个数。这n个人。每人选一个数字,要求相邻的两个人选择的数要么不相等,要么相等时大于k

    题解:dp[i][0]:第i个人选大于k的数的最优解,dp[i][1]:第i个人选小于等于k的数的最优解。

               则  dp[i][0]=(m-k)*dp[i-1][0]+(m-k)*dp[i-1][1]

                      dp[i][1]=k*dp[i-1][0]+(k-1)*dp[i-1][1].

               构造矩阵:  |  dp[i][0]     |           |  m-k ,m-k |         |  dp[i-1][0]  |

                                                                =                           *

                                     |  dp[i][1]     |          |   k     ,k-1  |          |   dp[i-1][1]  |

    #include<cstring>
    #include<cstdio>
    #include<algorithm>
    #include<iostream>
    #include<vector>
    #define ll long long
    #define mod 1000000007
    using namespace std;
    
    typedef vector<ll>vec;
    typedef vector<vec>mat;
    
    ll n,m,k;
    
    mat mul(mat &A,mat &B) {
        mat C(A.size(),vec(B[0].size()));
        for(int i=0; i<A.size(); i++) {
            for(int k=0; k<B.size(); k++) {
                for(int j=0; j<B[0].size(); j++) {
                    C[i][j]=(C[i][j]+A[i][k]*B[k][j])%mod;
                }
            }
        }
        return C;
    }
    
    mat pow_mod(mat A,ll x) {
        mat B(A.size(),vec(A.size()));
        for(int i=0; i<A.size(); i++) {
            B[i][i]=1;
        }
        while(x>0) {
            if(x&1)B=mul(B,A);
            A=mul(A,A);
            x>>=1;
        }
        return B;
    }
    
    int main() {
        //freopen("test.in","r",stdin);
        while(~scanf("%lld%lld%lld",&n,&m,&k)) {
            mat A(2,vec(2));
            A[0][0]=m-k,A[0][1]=m-k;
            A[1][0]=k,A[1][1]=k-1;
            A=pow_mod(A,n-1);
            ll ans=(A[0][0]+A[1][0])*(m-k)%mod+(A[0][1]+A[1][1])*k%mod;
            printf("%lld
    ",ans%mod);
        }
        return 0;
    }


  • 相关阅读:
    PHP如何计算两个时间之间相差多少时分秒
    关于php如何连贯操作类方法(以数据库为例)
    php中递归创建目录
    John细说PHP的验证码
    PHP内部函数使用外部变量的方法
    php中call_user_func_array()的使用
    linux-Centos6.5中nginx1.63源码安装
    shopnc 商城源码阅读笔记-缓存技术
    PHP引用传值规范问题
    shopnc 商城源码阅读笔记--开篇概述
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7147874.html
Copyright © 2011-2022 走看看