luogu 1357 花园 (状压dp+矩阵快速幂 推荐)

177 篇文章 0 订阅
77 篇文章 8 订阅

题目描述

小L有一座环形花园,沿花园的顺时针方向,他把各个花圃编号为1~N(2<=N<=10^15)。他的环形花园每天都会换一个新花样,但他的花园都不外乎一个规则,任意相邻M(2<=M<=5,M<=N)个花圃中有不超过K(1<=K<M)个C形的花圃,其余花圃均为P形的花圃。

例如,N=10,M=5,K=3。则

CCPCPPPPCC 是一种不符合规则的花圃;

CCPPPPCPCP 是一种符合规则的花圃。

请帮小L求出符合规则的花园种数Mod 1000000007

由于请您编写一个程序解决此题。

输入输出格式

输入格式:

一行,三个数N,M,K。

 

输出格式:

花园种数Mod 1000000007

 

输入输出样例

输入样例#1:

10 5 3

输出样例#1:

458

输入样例#2:

6 2 1

输出样例#2:

18

说明

【数据规模】

40%的数据中,N<=20;

60%的数据中,M=2;

80%的数据中,N<=10^5。

100%的数据中,N<=10^15。

题目链接:https://www.luogu.org/problemnew/show/P1357

题目分析:m很小,容易想到状压dp,dp[i][s]表示到i位置前m个状态为s时的方案数,环的话只需要枚举开头前m个位置的合法状态,最后累计dp[m+n][k]的值即可,k就是开头前m个位置所能组成的全部合法状态,但是对于最后20%的数据,N非常大,可以用矩阵的方式把转移优化成logn,转移矩阵通过枚举状压很容易预处理出来,对某个状态,删除第一个位置,在最后位置添0或添1

#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;
int const MOD = 1e9 + 7;
int const MAX = 35;
ll n;
int m, k, tot, sta[MAX];

struct Matrix {
    ll mat[MAX][MAX];
    Matrix() {
        memset(mat, 0, sizeof(mat));
    }
};

Matrix mul(Matrix a, Matrix b) {
    Matrix ans;
    for (int i = 0; i <= tot; i++) {
        for (int j = 0; j <= tot; j++) {
            for (int k = 0; k <= tot; k++) {
                ans.mat[i][k] += a.mat[i][j] * b.mat[j][k];
                ans.mat[i][k] %= MOD;
            }
        }
    }
    return ans;
}

Matrix qpow(Matrix a, ll n) {
    Matrix ans;
    for (int i = 0; i <= tot; i++) {
        ans.mat[i][i] = 1;
    }
    while (n) {
        if (n & 1) {
            ans = mul(ans, a);
        }
        a = mul(a, a);
        n >>= 1;
    }
    return ans;
}

int main() {
    Matrix res;
    scanf("%lld %d %d", &n, &m, &k);
    tot = (1 << m) - 1;
    for (int i = 0; i <= tot; i++) {
        int num = 0, tmp = i;
        while (tmp) {
            num += (tmp & 1);
            tmp >>= 1;
        }
        if (num <= k) {
            sta[i] = true;
            res.mat[i >> 1][i] = 1;
            res.mat[(i >> 1) | (1 << (m - 1))][i] = 1;
        }
    }
    res = qpow(res, n);
    ll ans = 0;
    for (int i = 0; i <= tot; i++) {
        if (sta[i]) {
            ans += res.mat[i][i];
            ans %= MOD;
        }
    }
    printf("%lld\n", ans);
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值