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);
}
相关推荐
爱读书的小胖19 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
Code_Solitude20 小时前
c语言:关于qsoet函数知识点
c语言·数据结构·算法
Nil20820 小时前
leetcode 49字母异位分组
算法·leetcode·哈希算法
鸽鸽程序猿20 小时前
【项目】【在线判题系统】c端:竞赛报名
c语言·开发语言
H.莓飛21 小时前
【Linux】自主 Shell
linux·运维·服务器·c语言·开发语言·visual studio
爱读书的小胖1 天前
Codewars:Last digit of a large number(C)解题分析
c语言·开发语言·r语言
lvwangshu1 天前
字符串 题解
字符串·trie·题解·贪心·技巧·性质题·思维好题
想做小南娘,发现自己是女生喵1 天前
第二周学习文档 Linux C 文件操作
linux·c语言·学习
Bluetooth7301 天前
c语言变量的存储类别
c语言
lhbweilai1 天前
分析FreeRTOS内核对象API的源码实现(四)
c语言·stm32·单片机