状态只会从a小转移到a大,随便dp就好了。
#include<bits/stdc++.h> using namespace std; const int N = 5000 + 7; const int mod = 998244353; int n, a[N], sum[N], dp[N][N], sum_dp[N]; int inv[N]; int main() { inv[1] = 1; for(int i = 2; i < N; i++) { inv[i] = 1LL * (mod - mod / i) * inv[mod % i] % mod; } scanf("%d", &n); for(int i = 1; i <= n; i++) { int x; scanf("%d", &x); a[x]++; } for(int i = 1; i < N; i++) { sum[i] = sum[i - 1] + a[i]; } dp[0][0] = 1; for(int j = 1; j <= n; j++) { sum_dp[0] = dp[0][j - 1]; for(int i = 1; i < N; i++) { sum_dp[i] = (sum_dp[i - 1] + dp[i][j - 1]) % mod; } for(int i = 1; i < N; i++) { dp[i][j] = 1LL * sum_dp[i - 1] * inv[n - j + 1] % mod * a[i] % mod; } } int ans = 0; for(int i = 1; i < N; i++) { if(a[i] < 2) continue; for(int j = 1; j < n; j++) { ans += 1LL * (a[i] - 1) * inv[n - j] % mod * dp[i][j] % mod; if(ans >= mod) ans -= mod; } } printf("%d\n", ans); return 0; } /* */