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);
}
相关推荐
逆小舟1 小时前
【C/C++】指针
c语言·c++·笔记·学习
earthzhang20211 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
迎風吹頭髮1 小时前
UNIX下C语言编程与实践63-UNIX 并发 Socket 编程:非阻塞套接字与轮询模型
java·c语言·unix
奔跑吧邓邓子2 小时前
【C语言实战(6)】解锁C语言循环密码:for循环实战探秘
c语言·实战·for循环
GilgameshJSS2 小时前
STM32H743-ARM例程15-RTC
c语言·arm开发·stm32·实时音视频
pu_taoc2 小时前
深入剖析:基于epoll与主从Reactor模型的高性能服务器设计与实现
服务器·c语言·c++·vscode
小欣加油4 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗4 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗4 小时前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
Mr.Ja4 小时前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器