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);
}
相关推荐
学不动CV了5 小时前
ARM单片机启动流程(二)(详细解析)
c语言·arm开发·stm32·单片机·51单片机
YuTaoShao6 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
猫猫的小茶馆7 小时前
【STM32】通用定时器基本原理
c语言·stm32·单片机·嵌入式硬件·mcu·51单片机
pumpkin845148 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
2401_858286119 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
双叶83610 小时前
(C++)学生管理系统(正式版)(map数组的应用)(string应用)(引用)(文件储存的应用)(C++教学)(C++项目)
c语言·开发语言·数据结构·c++
is081512 小时前
STM32的 syscalls.c 和 sysmem.c
c语言·stm32·嵌入式硬件
学不动CV了12 小时前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
百年孤独_14 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
算法_小学生15 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展