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);
}
相关推荐
小狗祈祷诗2 小时前
day22-数据结构之 栈&&队列
c语言·数据结构
AI+程序员在路上2 小时前
XML介绍及常用c及c++库
xml·c语言·c++
软行3 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
How_doyou_do3 小时前
备战菊厂笔试4
python·算法·leetcode
緈福的街口6 小时前
【leetcode】94. 二叉树的中序遍历
算法·leetcode
小刘要努力呀!6 小时前
嵌入式开发学习(第二阶段 C语言基础)
c语言·学习·算法
草莓熊Lotso7 小时前
【C语言字符函数和字符串函数(一)】--字符分类函数,字符转换函数,strlen,strcpy,strcat函数的使用和模拟实现
c语言·开发语言·经验分享·笔记·其他
小秋学嵌入式-不读研版8 小时前
C42-作业练习
c语言·开发语言·笔记
小羊在奋斗8 小时前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
QQ_4376643149 小时前
Linux下可执行程序的生成和运行详解(编译链接汇编图解)
linux·运维·c语言·汇编·caffe