这题很明显存在一个递推关系,思考了一下果然如此。
设dp[i][j]为前i项的和膜p为j的方案数,显然dp[i+1][j] = sum(dp[i][k]), (k + j != p), 那么问题来了,i和j的取值都为1e9,这个数组显然开不出来,开出来了也会超时。
我们观察可以发现,其实对每个j只有唯一一个k能使k + j == p, 可以算出k刚好取到1到p-1, 当我们求长度为i的总方案数时,可以看作加上了P-1个i-1的总方案数再减去一个sum(dp[i][k], k = 1 to p-1), 考虑优化空间 dp[i] = dp[i - 1] * (p - 1) - dp[i - 1] = dp[i - 1] * (p - 2);
dp[1] = p - 1;
dp[n] = dp[1] * pow(p - 2, n - 1);
n为1e9,用快速幂优化;
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 1e5 + 10;
const int M_MAX = 50000 + 10;
const int mod = 1e9 + 7;
const LL INF = 1e17;
const double eps = 1e-6;
LL quic_pow(LL x, LL n) {
LL res = 1;
while(n) {
if(n & 1) res = res * x % mod;
x = x * x % mod;
n >>= 1;
}
return res;
}
void solve() {
int n, p;
cin >> n >> p;
LL ans = quic_pow((p-2), n-1) % mod * (p-1) % mod;
cout << ans;
}
int main()
{
ios::sync_with_stdio(false);
//freopen("D:\\in.txt", "r", stdin);
solve();
return 0;
}