标签:贪心
描述
有一个长度为 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; // 好习惯
}