classSolution { private: staticconstexprint mod = 1000000007;
public: intkInversePairs(int n, int k){ vector<vector<int>> f(2, vector<int>(k + 1)); f[0][0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j <= k; ++j) { int cur = i & 1, prev = cur ^ 1; f[cur][j] = (j - 1 >= 0 ? f[cur][j - 1] : 0) - (j - i >= 0 ? f[prev][j - i] : 0) + f[prev][j]; if (f[cur][j] >= mod) { f[cur][j] -= mod; } elseif (f[cur][j] < 0) { f[cur][j] += mod; } } } return f[n & 1][k]; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { publicintkInversePairs(int n, int k) { finalintMOD=1000000007; int[][] f = newint[2][k + 1]; f[0][0] = 1; for (inti=1; i <= n; ++i) { for (intj=0; j <= k; ++j) { intcur= i & 1, prev = cur ^ 1; f[cur][j] = (j - 1 >= 0 ? f[cur][j - 1] : 0) - (j - i >= 0 ? f[prev][j - i] : 0) + f[prev][j]; if (f[cur][j] >= MOD) { f[cur][j] -= MOD; } elseif (f[cur][j] < 0) { f[cur][j] += MOD; } } } return f[n & 1][k]; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicintKInversePairs(int n, int k) { constint MOD = 1000000007; int[,] f = newint[2, k + 1]; f[0, 0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j <= k; ++j) { int cur = i & 1, prev = cur ^ 1; f[cur, j] = (j - 1 >= 0 ? f[cur, j - 1] : 0) - (j - i >= 0 ? f[prev, j - i] : 0) + f[prev, j]; if (f[cur, j] >= MOD) { f[cur, j] -= MOD; } elseif (f[cur, j] < 0) { f[cur, j] += MOD; } } } return f[n & 1, k]; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defkInversePairs(self, n: int, k: int) -> int: mod = 10**9 + 7 f = [1] + [0] * k for i inrange(1, n + 1): g = [0] * (k + 1) for j inrange(k + 1): g[j] = (g[j - 1] if j - 1 >= 0else0) - (f[j - i] if j - i >= 0else0) + f[j] g[j] %= mod f = g return f[k]