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);
}
相关推荐
程序leo源6 分钟前
Qt信号与槽深度详解
c语言·开发语言·数据库·c++·qt·c#
老四啊laosi17 分钟前
[滑动窗口] 12. 将 x 减到 0 的最小操作数
算法·leetcode·将 x 减到 0 的最小操作数
Simple-Soft1 小时前
指针的高级应用与技巧 - C语言的灵魂
c语言·数据结构·算法
努力努力再努力wz2 小时前
【C++高阶数据结构系列】:时间轮定时器详解:原理分析与代码实现,带你从零手撕时间轮!(附时间轮的实现源码)
c语言·开发语言·数据结构·c++·qt·算法·ui
水饺编程2 小时前
编程基础:令牌粘贴指令,【##】
c语言·c++·windows·visual studio
Chen_harmony2 小时前
十九、数据在内存中的存储
c语言·开发语言
basketball6162 小时前
C 的 malloc/free 与 C++ 的 new/delete 一些区别
c语言·开发语言·c++
爱编码的小八嘎2 小时前
MFC深入-消息映射的实现
c语言
人道领域2 小时前
【LeetCode刷题日记】513.二叉树左下角值的三种解法:从常规BFS到DFS的优雅之旅
数据结构·算法·leetcode·深度优先·广度优先
我命由我123453 小时前
Visual Studio - Visual Studio 注释快捷键
java·c语言·开发语言·c++·ide·java-ee·visual studio