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);
}
相关推荐
希望有朝一日能如愿以偿37 分钟前
力扣每日一题:统计梯形的数目
算法·leetcode·职场和发展
水饺编程2 小时前
第3章,[标签 Win32] :WM_CREATE 消息的产生
c语言·c++·windows·visual studio
会员果汁2 小时前
双向链式队列-C语言
c语言·数据结构
C语言不精2 小时前
c语言-优雅的多级菜单设计与实现
c语言·开发语言·算法
jyyyx的算法博客3 小时前
LeetCode 面试题 16.22. 兰顿蚂蚁
算法·leetcode
Q741_1473 小时前
C++ 高精度计算的讲解 模拟 力扣67.二进制求和 题解 每日一题
c++·算法·leetcode·高精度·模拟
leoufung3 小时前
LeetCode 98 Validate Binary Search Tree 深度解析
算法·leetcode·职场和发展
jyyyx的算法博客3 小时前
LeetCode 面试题 16.18. 模式匹配
算法·leetcode
star learning white4 小时前
xmC语言10
c语言·开发语言
ada7_4 小时前
LeetCode(python)——94.二叉
python·算法·leetcode·链表·职场和发展