题解:B4373 [GXPC-S 2025] 队伍集结 / team

· · 题解

题解

PART 1🙃:题目解释(审题)

这道题要求我们在一条无限长的直线上选择最多k个汇合点,使得所有同学的不满意度总和最小。每个同学的不满意度是距离最近的汇合点与自己的位置的差的平方再乘以个不满意系数。我们需要找到最优的汇合点位置和分配方案。

PART 2:代码思路

方法思路

排序&预处理:首先将所有同学的位置按升序排序,这样我们可以方便地处理相邻的同学。

状态转移:对于每个$i$和$j$,我们需要找到之前的一个点$m$,将$m+1到i$的同学分成一组,并计算这一组的最小不满意度。即$dp[i][j] = min(dp[m][j-1] + cost[m+1][i])$,其中$cost[m+1][i]$表示将第$m+1$到$i$的同学分成一组时的最小不满意度。 计算$cost$数组:$cost[l][r]$表示将位置在$l$到$r$的同学合并到一个组时的最小不满意度。最优的汇合点应该位于这些同学位置的加权中位数附近,以最小化平方误差的加权和。 下面就是我钻研10000000000000000000000*1e100年的 # $AC Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Person {
    int a;
    ll b;
};

bool compare(const Person &x, const Person &y) {
    return x.a < y.a;
}

int main() {
    int n, k;
    cin >> n >> k;
    vector<Person> people(n);
    for (int i = 0; i < n; ++i) {
        cin >> people[i].a >> people[i].b;
    }
    sort(people.begin(), people.end(), compare);
    vector<vector<ll>> cost(n, vector<ll>(n, 0));
    for (int l = 0; l < n; ++l) {
        for (int r = l; r < n; ++r) {
            ll total_b = 0;
            ll weighted_sum = 0;
            for (int i = l; i <= r; ++i) {
                total_b += people[i].b;
                weighted_sum += people[i].b * people[i].a;
            }
            if (total_b == 0) {
                cost[l][r] = 0;
                continue;
            }
            ll mean = weighted_sum / total_b;
            ll min_cost = LLONG_MAX;

            for (ll x = mean - 1; x <= mean + 1; ++x) {
                if (x < 0) continue; 
                ll current_cost = 0;
                for (int i = l; i <= r; ++i) {
                    ll diff = people[i].a - x;
                    current_cost += diff * diff * people[i].b;
                }
                if (current_cost < min_cost) {
                    min_cost = current_cost;
                }
            }
            cost[l][r] = min_cost;
        }
    }
    vector<vector<ll>> dp(n + 1, vector<ll>(k + 1, LLONG_MAX));
    dp[0][0] = 0;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= k; ++j) {
            for (int m = 0; m < i; ++m) {
                if (dp[m][j - 1] != LLONG_MAX) {
                    ll new_cost = dp[m][j - 1] + cost[m][i - 1];
                    if (new_cost < dp[i][j]) {
                        dp[i][j] = new_cost;
                    }
                }
            }
        }
    }

    cout << dp[n][k] << endl;
    return 0;
}