矩阵连乘,爆米花桶,2023/9/23,组队赛

文章介绍如何用矩阵快速计算多层爆米花桶所需纸张面积,涉及矩阵连乘、快速幂等算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Contest (nefu.edu.cn)

Problem:C
Time Limit:1000ms
Memory Limit:65535K

Description

Alice和Bob想吃爆米花,可是他们没有爆米花桶,想叠一个n层的爆米花桶,但是他们不知道叠一个n层的桶需要多大的纸,他们来请教你。
f[i]为叠一个i层的爆米花桶需要的纸的面积,叠一层时需要面积为a的纸,叠两层需要面积为b的纸,叠i层需要面积为f[i]=f[i-1]+f[i+1]的纸
请你告诉他们叠一个n层的爆米花桶需要多大面积的纸壳,并对1e9+7取模

Input

输入为多组
第一行有三个数 n,a,b
n,a,b<=1e8

Output

面积并取模

Sample Input

3 2 1

Sample Output

1000000006

解析:

最简单的矩阵连乘,当时脑抽了,没看到有多组输入

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
const int N = 1e6 + 5,mod=1e9+7;
typedef struct matrix {
	LL m[2][2];
}matrix;

matrix P = { 1,-1,1,0 };
matrix I = { 1,0,0,1 };
LL n,a, b;

matrix mul(matrix ma, matrix mb) {
	matrix c;
	for (int i = 0; i < 2; i++) {
		for (int j = 0; j < 2; j++) {
			c.m[i][j] = 0;
			for (int k = 0; k < 2; k++) {
				c.m[i][j] = (c.m[i][j] + (ma.m[i][k] * mb.m[k][j])%mod) % mod;
			}
		}
	}
	return c;
}

matrix quickmul(int in) {
	matrix ret = I, t = P;
	while (in) {
		if (in & 1) {
			ret=mul(ret, t);
		}
		t=mul(t, t);
		in >>= 1;
	}
	return ret;
}

int main() {
	while (scanf("%lld%lld%lld", &n, &a, &b) != EOF) {
		a %= mod;
		b %= mod;
		matrix ret = quickmul(n - 2);
		if (n == 1)
			cout << a % mod << endl;
		else {
			LL ans = ((ret.m[0][0] * b) % mod + (ret.m[0][1] * a) % mod+mod ) % mod;
			cout << ans << endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值