|
| 1 | +using LL = long long; |
| 2 | +LL M = 1e9+7; |
| 3 | +class Solution { |
| 4 | + long long comb[1005][6]; |
| 5 | +public: |
| 6 | + LL getComb(int m, int n) |
| 7 | + { |
| 8 | + if (m<n) return 0; |
| 9 | + return comb[m][n]; |
| 10 | + } |
| 11 | + |
| 12 | + int subsequencesWithMiddleMode(vector<int>& nums) |
| 13 | + { |
| 14 | + int n = nums.size(); |
| 15 | + for (int i = 0; i <= n; ++i) |
| 16 | + { |
| 17 | + comb[i][0] = 1; |
| 18 | + if (i==0) continue; |
| 19 | + for (int j = 1; j <= 5; ++j) |
| 20 | + { |
| 21 | + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; |
| 22 | + comb[i][j] %= M; |
| 23 | + } |
| 24 | + } |
| 25 | + unordered_set<int>Set(nums.begin(), nums.end()); |
| 26 | + |
| 27 | + LL ret = 0; |
| 28 | + |
| 29 | + unordered_map<int,int>left; |
| 30 | + unordered_map<int,int>right; |
| 31 | + for (int x: nums) right[x]++; |
| 32 | + |
| 33 | + for (int i=0; i<n; i++) |
| 34 | + { |
| 35 | + int a = nums[i]; |
| 36 | + right[a]--; |
| 37 | + if (i>=1) left[nums[i-1]]++; |
| 38 | + |
| 39 | + ret += getComb(i - left[a], 2) * getComb(n-i-1-right[a], 2) %M; |
| 40 | + ret %= M; |
| 41 | + |
| 42 | + for (int b: Set) |
| 43 | + { |
| 44 | + if (a==b) continue; |
| 45 | + ret += getComb(left[b],2) * getComb(right[a], 1) * getComb(n-i-1-right[a]-right[b], 1) %M; |
| 46 | + ret += getComb(right[b],2) * getComb(left[a], 1) * getComb(i-left[a]-left[b], 1) %M; |
| 47 | + ret %= M; |
| 48 | + } |
| 49 | + |
| 50 | + for (int b: Set) |
| 51 | + { |
| 52 | + if (a==b) continue; |
| 53 | + ret += getComb(left[b],1) * getComb(i-left[b]-left[a], 1) * getComb(right[a], 1) * getComb(right[b], 1) %M; |
| 54 | + ret += getComb(right[b],1) * getComb(n-i-1-right[b]-right[a], 1) * getComb(left[a], 1) * getComb(left[b], 1) %M; |
| 55 | + ret %= M; |
| 56 | + } |
| 57 | + |
| 58 | + for (int b: Set) |
| 59 | + { |
| 60 | + if (a==b) continue; |
| 61 | + ret += getComb(left[b],2) * getComb(right[a], 1) * getComb(right[b], 1) %M; |
| 62 | + ret += getComb(right[b],2) * getComb(left[a], 1) * getComb(left[b], 1) %M; |
| 63 | + ret %= M; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return (getComb(n, 5) - ret + M) % M; |
| 68 | + } |
| 69 | +}; |
0 commit comments