题目描述
众所周知丑数是非常神奇的数字,虽然他叫丑数,但是他看起来就特别的美妙。现在我们需要从小到大找到第a个和第b个丑数。(a<b)分别设为f(1)和f(2)。现在我们需要求的f(n)也是一个美妙的数字,已知 f ( x ) = 2 ∗ f ( x − 1 ) + 3 ∗ f ( x − 2 ) f(x)=2*f(x-1)+3*f(x-2) f(x)=2∗f(x−1)+3∗f(x−2)其中(x>2),求f(n)到底为多少,答案对mod=1e9+7取模。
(丑数指只由分解后只由若干个2,3,5相乘。默认1为第一个丑数)
输入描述:
第一行输入三个整数a,b,n(1<=a<=b<=5*104,1<=n<=109)
输出描述:
输出f(n)对mod取余的结果(mod=1e9+7)
示例1
输入
1 2 3
输出
7
说明
第一个丑数是1,第二个丑数是2,f(3)=3*f(1)+2*f(2)=3*1+2*2=7
示例2
输入
3 5 10
输出
39365
#include<bits/stdc++.h>
using namespace std;
template <typename T> void debug(string s, T x) { cout << s << "=" << x << "\n"; }
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pll;
typedef pair<int, int>pii;
const ll N = 1e5+5;
const ll MOD = 1e9 + 7;
const ll INF = 0x7fffffff;
const ll MAXN = 2;//矩阵的阶
struct Matrix {
ll m[MAXN][MAXN];
Matrix() { memset(m, 0, sizeof(m)); }
};
Matrix Multi(Matrix a, Matrix b) {// 矩阵乘法
Matrix ans;
for (int i = 0; i < MAXN; ++i) {
for (int j = 0; j < MAXN; ++j) {
for (int k = 0; k < MAXN; ++k) {
ans.m[i][j] = (ans.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
}
}
}
return ans;
}
Matrix fastm(Matrix a, ll n) {
Matrix ans;
for (int i = 0; i < MAXN; i++)ans.m[i][i] = 1;//初始化为单位矩阵
while (n > 0) {
if (n & 1)ans = Multi(ans, a);
a = Multi(a, a);
n >>= 1;
}
return ans;
}
__int128 findUgly(int n) {
priority_queue<__int128, vector<__int128>, greater<__int128>> Q;
Q.push(1);
__int128 ans = 1, i = 1;
while (i <= n) {
Q.push(ans * 2);
Q.push(ans * 3);
Q.push(ans * 5);
ans = Q.top();
Q.pop();
while (!Q.empty() && ans == Q.top()) Q.pop();
++i;
}
return ans;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int a, b, n;
cin >> a >> b >> n;
__int128 f1=findUgly(a)%MOD, f2=findUgly(b)%MOD;
Matrix ans, A, B;
//[fn-1,fn-2]*B=[fn,fn-1]
A.m[0][0] = f2; A.m[0][1] = f1;//A=[f2,f1]
B.m[0][0] = 2; B.m[0][1] = 1;
B.m[1][0] = 3; B.m[1][1] = 0;
ans = Multi(A, fastm(B, n - 1));
cout << ans.m[0][1] << "\n";
return 0;
}