P15569 [COCI 2025/2026 #5] 结构 / Struktura
题意简述
一个长度为 的序列 ,每一位在 中随机选取一个值,求序列是排列且满足对于每一个 都有 的概率。
题目解法
首先我们看一下第二条限制,可以转化为 。
如图所示:
构造几组样例玩一下,发现合法方案数是斐波那契数,写一下试试,套个矩乘,AC了!
让我们试着证一下。考虑数列末尾,取值只能是 或 。
如果选择 ,则上一个无法选择 ,发现 处和情况现在一样。
如果选择 ,则上一个只能选择 ,否则之后就选不到 了,那么 处情况和现在一样。
总方案数就是 ,所以答案就是 , 表示斐波那契数列第 项。
附代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
const int mod = 1e9+7;
int qpow(int a, int b = mod-2) {
int res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
struct Matrix {
int a[2][2];
Matrix() { memset(a, 0, sizeof a); }
Matrix operator*(const Matrix& other) const {
Matrix res;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
res.a[i][j] = (res.a[i][j] + a[i][k] * other.a[k][j]) % mod;
return res;
}
};
Matrix matpow(Matrix a, int b) {
Matrix res;
res.a[0][0] = res.a[1][1] = 1;
while (b) {
if (b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
signed main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int n, k;
cin >> n >> k;
if (k < n) {
cout << 0 << endl;
return 0;
}
if (n == 1) {
cout << qpow(k) << endl;
return 0;
}
Matrix base;
base.a[0][0] = 1; base.a[0][1] = 1;
base.a[1][0] = 1; base.a[1][1] = 0;
Matrix res = matpow(base, n);
int fn = res.a[0][0];
int total = qpow(k, n);
int ans = fn * qpow(total) % mod;
cout << ans << endl;
return 0;
}

