classSolution{public:longlongminimumTotalDistance(vector<int>& a, vector<vector<int>>& fac){sort(a.begin(), a.end());sort(fac.begin(), fac.end());int n = a.size(), m = fac.size();
vector<vector<longlong>>f(n +1,vector<longlong>(m +1,0));
vector<vector<longlong>>d(n +1,vector<longlong>(m +1,0));for(int j =0; j < m; j ++)for(int i = n -1; i >=0; i --)
d[i][j]= d[i +1][j]+abs(a[i]- fac[j][0]);
function<longlong(int,int)> dfs =[&](int i,int j)->longlong{if(f[i][j])return f[i][j];if(i == n)return0ll;if(j == m -1){if(n - i > fac[j][1])return1e18;return d[i][j];}
f[i][j]=dfs(i, j +1);longlong s =0, k =1;while(k <= fac[j][1]&& i + k -1< n){
s +=abs(a[i + k -1]- fac[j][0]);
f[i][j]=min(f[i][j], s +dfs(i + k, j +1));
k ++;}return f[i][j];};returndfs(0,0);}};
dp写法
classSolution{public:longlongminimumTotalDistance(vector<int>&a, vector<vector<int>>&fac){sort(fac.begin(), fac.end());sort(a.begin(), a.end());int n = a.size();
vector<longlong>f(n +1,1e18);
f[0]=0;for(auto&fa: fac)for(int j = n; j >0; j--){longlong cost =0ll;for(int k =1; k <=min(j, fa[1]); k ++){
cost +=abs(a[j - k]- fa[0]);
f[j]=min(f[j], f[j - k]+ cost);}}return f[n];}};