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);
}
相关推荐
叫我辉哥e17 小时前
### 技术文章大纲:C语言造轮子大赛
c语言·开发语言
TracyCoder1238 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
进击的小头10 小时前
行为型模式:策略模式的C语言实战指南
c语言·开发语言·策略模式
爱编码的小八嘎11 小时前
C语言对话-5.通过任何其他名字
c语言
weixin_4454766812 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王12 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区12 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展
定偶13 小时前
C语言入门指南
c语言·开发语言
期末考复习中,蓝桥杯都没时间学了13 小时前
力扣刷题10
算法·leetcode·职场和发展
的卢马飞快14 小时前
【C语言进阶】给数据一个“家”:从零开始掌握文件操作
c语言·网络·数据库