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);
}
相关推荐
枫叶丹417 分钟前
【Qt开发】Qt系统(一)-> 定时器 QTimerEvent 和 QTimer
c语言·开发语言·数据库·c++·qt·系统架构
元亓亓亓7 小时前
LeetCode热题100--416. 分割等和子集--中等
算法·leetcode·职场和发展
YGGP10 小时前
【Golang】LeetCode 32. 最长有效括号
算法·leetcode
自然常数e11 小时前
字符函数和字符串函数
c语言·算法·visual studio
山上三树11 小时前
main()函数带参数的用法
linux·c语言
lengjingzju11 小时前
一网打尽Linux IPC(一):进程间通信完全指南——总体介绍
linux·服务器·c语言
YGGP13 小时前
【Golang】LeetCode 5. 最长回文子串
算法·leetcode
hqyjzsb13 小时前
从爱好到专业:AI初学者如何跨越CAIE认证的理想与现实鸿沟
大数据·c语言·人工智能·信息可视化·职场和发展·excel·业界资讯
历程里程碑14 小时前
滑动窗口解法:无重复字符最长子串
数据结构·c++·算法·leetcode·职场和发展·eclipse·哈希算法
Felven14 小时前
C. Maximum Median
c语言·开发语言·算法