C语言 | Leetcode C语言题解之第552题学生出勤记录II

题目:

题解:

cpp 复制代码
const int MOD = 1000000007;

struct Matrix {
    long mat[6][6];
    int row, col;
};

struct Matrix multiply(struct Matrix a, struct Matrix b) {
    int rows = a.row, columns = b.col, temp = b.row;
    struct Matrix c;
    memset(c.mat, 0, sizeof(c.mat));
    c.row = rows, c.col = columns;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            for (int k = 0; k < temp; k++) {
                c.mat[i][j] += a.mat[i][k] * b.mat[k][j];
                c.mat[i][j] %= MOD;
            }
        }
    }
    return c;
}

struct Matrix matricPow(struct Matrix mat, int n) {
    struct Matrix ret = {{{1, 0, 0, 0, 0, 0}}, 1, 6};
    while (n > 0) {
        if ((n & 1) == 1) {
            ret = multiply(ret, mat);
        }
        n >>= 1;
        mat = multiply(mat, mat);
    }
    return ret;
}

int checkRecord(int n) {
    struct Matrix mat = {{{1, 1, 0, 1, 0, 0}, {1, 0, 1, 1, 0, 0}, {1, 0, 0, 1, 0, 0}, {0, 0, 0, 1, 1, 0}, {0, 0, 0, 1, 0, 1}, {0, 0, 0, 1, 0, 0}}, 6, 6};
    struct Matrix res = matricPow(mat, n);
    long sum = 0;
    for (int i = 0; i < res.col; i++) {
        sum += res.mat[0][i];
    }
    return (int)(sum % MOD);
}
相关推荐
小雅痞20 分钟前
[Java][Leetcode middle] 209. 长度最小的子数组
java·算法·leetcode
努力努力再努力wz2 小时前
【MySQL进阶系列】一文打通事务机制:从锁、Undo Log 到 MVCC 与隔离级别
c语言·数据结构·数据库·c++·mysql·算法·github
薇茗2 小时前
【初阶数据结构】 左右逢源的分支诗律 二叉树1
c语言·数据结构·算法
eDEs OLDE3 小时前
CC++链接数据库(MySQL)超级详细指南
c语言·数据库·c++
浅念-3 小时前
吃透栈:LeetCode 栈算法题全解析
数据结构·c++·算法·leetcode·职场和发展·
阿Y加油吧3 小时前
二刷 LeetCode:62. 不同路径 & 64. 最小路径和 复盘笔记
笔记·算法·leetcode
承渊政道3 小时前
【动态规划算法】(两个数组的DP问题深度剖析与求解方法)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
广州山泉婚姻4 小时前
C语言三种基本程序结构详解
c语言·开发语言
上弦月-编程4 小时前
【C语言】函数栈帧的创建与销毁(底层原理)
c语言·开发语言
加农炮手Jinx4 小时前
LeetCode 26. Remove Duplicates from Sorted Array 题解
算法·leetcode·力扣