fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int INF = -1e9;
  5. int maximumTotalWeight(int k, int n, int m, vector<pair<int,int>>& clusters) {
  6. // Initialize two DP arrays for current and previous DP state
  7. vector<vector<int>> dpCurrent(n+1, vector<int>(m+1, INF));
  8. vector<vector<int>> dpPrevious(n+1, vector<int>(m+1, INF));
  9.  
  10. dpPrevious[0][0] = 0; // Base case: no clusters, no elements chosen
  11.  
  12. // Iterate through all clusters
  13. for(int i = 1; i <= k; i++) {
  14. int weightOfFirstGroup = clusters[i-1].first;
  15. int weightOfSecondGroup = clusters[i-1].second;
  16.  
  17. for(int x = 0; x <= n; x++) {
  18. for(int y = 0; y <= m; y++) {
  19. // Case 1: Do not choose this cluster
  20. dpCurrent[x][y] = dpPrevious[x][y];
  21.  
  22. // Case 2: Choose this cluster for group 1
  23. if(x > 0) {
  24. dpCurrent[x][y] = max(dpCurrent[x][y], dpPrevious[x-1][y] + weightOfFirstGroup);
  25. }
  26.  
  27. // Case 3: Choose this cluster for group 2
  28. if(y > 0) {
  29. dpCurrent[x][y] = max(dpCurrent[x][y], dpPrevious[x][y-1] + weightOfSecondGroup);
  30. }
  31. }
  32. }
  33.  
  34. // Swap the current and previous states for the next iteration
  35. swap(dpCurrent, dpPrevious);
  36. }
  37.  
  38. return dpPrevious[n][m];
  39. }
  40.  
  41. int main() {
  42. int k, n, m; cin >> k >> n >> m;
  43. vector<pair<int,int>> clusters(k);
  44. for(auto& x : clusters) cin >> x.first >> x.second;
  45.  
  46. cout << maximumTotalWeight(k, n, m, clusters);
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5284KB
stdin
4 2 1
4 9
3 5
7 2
5 5
stdout
21