跳到正文

题解

abc360_c Move It tj

_colin1112_约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

思路

贪心地想,我们移动物品所需的代价越少越好,所以我们只需对有着大于一个物品的箱子进行排序,依次减去需要代价最小的一个物品,减到每个箱子内只有一个物品即可。

Code

C++
#include <bits/stdc++.h>
#define endl '\n'
#define ll long long

using namespace std;
const int E = 1e6 + 5;
ll n;
ll a[E], w[E];
vector<ll> cnt[E];
int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    for (int i = 1; i <= n; i++)
        cin >> w[i];
    for (int i = 1; i <= n; i++)
        cnt[a[i]].push_back(w[i]);
    for (int i = 1; i <= n; i++)
        if (cnt[i].size() > 1)
            sort(cnt[i].begin(), cnt[i].end(), greater<ll>());//对有着大于一个物品的箱子进行排序
    ll ans = 0;
    for (int i = 1; i <= n; i++)
    {
        if (cnt[i].size() > 1)
            while (1)
            {
                ans += *(cnt[i].end() - 1);//计算代价
                cnt[i].pop_back();//将最小的一个去除
                if (cnt[i].size() == 1)
                    break;//减到箱子内只有一个物品为止
            }
    }
    cout << ans;
    return 0;
}
原文