AcWing:5395. 平均

标签:贪心

 描述

有一个长度为 n的数组(n是 10 的倍数),每个数 ai都是区间 [0,9]中的整数。

小明发现数组里每种数出现的次数不太平均,而更改第 i 个数的代价为 bi,他想更改若干个数的值使得这 10 种数出现的次数相等(都等于 n/10),请问代价和最少为多少。

输入格式

输入的第一行包含一个正整数 n。

接下来 n 行,第 i 行包含两个整数 ai,bi,用一个空格分隔。

输出格式

输出一行包含一个正整数表示答案。

数据范围

对于 20% 的评测用例,n≤1000;
对于所有评测用例,n≤10^5,0<bi≤2×10^5。

输入样例:
10
1 1
1 2
1 3
2 4
2 5
2 6
3 7
3 8
3 9
4 10
输出样例:
27
样例解释

只更改第 1,2,4,5,7,81,2,4,5,7,8 个数,需要花费代价 1+2+4+5+7+8=27.

对于该题,应该是将超出的数字,取代价小的直接加上,我们可以使用sort进行倒序排序

代价大的先跳过,直到超过,开始ans加上超过的代价

#include <bits/stdc++.h>

using namespace std;

/* 依据题意 */
#define a first
#define b second
const int N = 1e5 + 10;
typedef long long LL;

/* 设立变量 */
typedef pair<LL, LL> PII;
int n , A , B;
PII numbers[N];

/* sort排序依据b的大小来排 */
bool cmp(PII x , PII y)
{
    return x.b >= y.b;
}

int main()
{
    /* 正常读入 */
    cin >> n;
    for (int i = 0; i < n; i ++ )
    {
        cin >> A >> B;
        numbers[i] = {A , B};
    }
    
    /* 排序 */
    sort(numbers , numbers + n , cmp);
    
    /* 初始化 */
    int avg = n / 10;
    LL cnt[10]; 
    memset(cnt, 0, sizeof cnt);
    LL ans = 0;
    
    /* 对数字计数 , 超出就加上 */
    for (int i = 0; i < n; i ++ )
    {
        cnt[numbers[i].a] ++;
        if(cnt[numbers[i].a] <= avg) continue;
        ans += numbers[i].b;
    }
    
    cout << ans;
}

 很遗憾,不知道为什么,10^5的样例,上述代码输出不了(也许是pair存不了这么多?

bool中的 = 号去掉就过了.

附上y总的教导:

y总:cmp函数返回的是a是否应该排到b的前面,相当于重载的小于号,

如果写等号的话,相当于 a < b和b < a都成立,这样定义的小于号会导致不确定结果

所以改变策略,用vector存0~9各个数字,对各个数字单独排序.

以下是AC代码:

#include <bits/stdc++.h>

using namespace std;

/* 依据题意 */
#define a first
#define b second
const int N = 1e5 + 10;
typedef long long LL;
typedef pair<LL, LL> PII;


int n , A , B;
PII numbers[N];
vector<vector<int>> num(10);

int main()
{
    /* 正常读入 */
    cin >> n;
    for (int i = 0; i < n; i ++ )
    {
        cin >> A >> B;
        numbers[i] = {A , B};
    }
    
    /* 存入vector中 */
    for (int i = 0; i < n; i ++ )
    {
        num[numbers[i].a].push_back(numbers[i].b);
    }
    
    /* 对每个数字进行快排 */
    for (int i = 0; i < 10; i ++ )
        sort(num[i].begin() , num[i].end());

    /* 初始化 */
    int avg = n / 10;
    LL ans = 0;
    
    /* 核心 */
    /* 如果数字不够直接跳过 */
    /* 如果超出就加代价小的 */ 
    for (int i = 0; i < 10; i ++ )
    {
        if (num[i].size() <= avg) continue;
        for (int j = 0; j < num[i].size() - avg; j ++)
            ans += num[i][j];
    }
    
    cout << ans; 
    return 0; // 好习惯
}
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值