Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://www.desiqna.in/11238/aesthetic-permutation-triology-codenation-dynamic-programming
- Perfect ๐
- Let me give you a **cleaner C++ implementation** with clear comments, that solves the same problem in a much easier-to-follow way.
- ---
- ### ๐น Key idea (simplified)
- * Sort the array `A`.
- * We must split the sorted array into `B` subsequences.
- * Each subsequence contributes cost = (last - first) of that subsequence.
- * So the problem reduces to **partitioning the sorted array into `B` subsequences optimally**.
- We can solve this with **DP** in a neat way.
- ---
- ### ๐น Simplified C++ solution
- ```cpp
- #include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- int main() {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- int N, B;
- cin >> N >> B;
- vector<ll> A(N);
- for (int i = 0; i < N; i++) cin >> A[i];
- // Step 1: Sort array
- sort(A.begin(), A.end());
- // Step 2: Precompute prefix differences
- vector<ll> diff(N+1, 0);
- for (int i = 1; i < N; i++) {
- diff[i+1] = diff[i] + (A[i] - A[i-1]);
- }
- // Step 3: Group sizes
- int small = N / B; // smaller group size
- int large = small + 1; // larger group size
- int countLarge = N % B; // number of groups with 'large' size
- int countSmall = B - countLarge;
- // Step 4: DP
- // dp[i][j] = min cost using i small groups and j large groups
- vector<vector<ll>> dp(countSmall+1, vector<ll>(countLarge+1, 1e18));
- dp[0][0] = 0;
- for (int i = 0; i <= countSmall; i++) {
- for (int j = 0; j <= countLarge; j++) {
- int used = i*small + j*large;
- if (used >= N) continue;
- // Take one more small group
- if (i < countSmall) {
- int l = used;
- int r = used + small - 1;
- ll cost = A[r] - A[l];
- dp[i+1][j] = min(dp[i+1][j], dp[i][j] + cost);
- }
- // Take one more large group
- if (j < countLarge) {
- int l = used;
- int r = used + large - 1;
- ll cost = A[r] - A[l];
- dp[i][j+1] = min(dp[i][j+1], dp[i][j] + cost);
- }
- }
- }
- cout << dp[countSmall][countLarge] << "\n";
- return 0;
- }
- ```
- ---
- ### ๐น Why this is simpler
- 1. Sorts array first.
- 2. Splits into `B` groups.
- 3. Uses **clear DP table** โ each entry means "minimum cost using X small groups and Y large groups".
- 4. Transition is easy: add next group of size `small` or `large`.
- ---
- โ This produces the same result as your sirโs code but is **much easier to read and understand**.
- Do you want me to also **draw a step-by-step dry run** for one of the sample test cases (like `A = [4,3,4,3,2,5], B = 3`) so itโs crystal clear?
Advertisement
Add Comment
Please, Sign In to add comment