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);
}
相关推荐
leoufung11 分钟前
用 DFS 拓扑排序吃透 LeetCode 210:Course Schedule II
算法·leetcode·深度优先
Swift社区1 小时前
LeetCode 443. 压缩字符串
leetcode·职场和发展·蓝桥杯
ada7_1 小时前
LeetCode(python)——543.二叉树的直径
数据结构·python·算法·leetcode·职场和发展
啊森要自信1 小时前
【STM32】USART串口通信
c语言·开发语言·stm32·单片机·嵌入式硬件
sprintzer1 小时前
11.26-12.05力扣栈刷题
算法·leetcode·职场和发展
sin_hielo2 小时前
leetcode 3578
数据结构·算法·leetcode
前端小白在前进2 小时前
力扣刷题:无重复字符的最长子串
算法·leetcode·职场和发展
4311媒体网2 小时前
C语言实现简单的二分查找算法
c语言·开发语言·算法
无限进步_3 小时前
C语言实现贪吃蛇游戏详解
c语言·开发语言·数据结构·c++·后端·算法·游戏
好易学·数据结构3 小时前
可视化图解算法72:斐波那契数列
数据结构·算法·leetcode·动态规划·力扣·牛客网