洛谷 P6236 [COCI2010-2011#1] LJUTNJA (尚贤)

题目传送门

贪心!!!

贪心思想:让分完糖果后得 最大值 最小

AC代码1

#include<bits/stdc++.h>
using namespace std;
long long a[100001],ans,n,m,maxx,qwq=1;//注意开 long long 
bool cmp(long long x,long long y)//手打 cmp 
{
    return x>y;//降幂排列 
}
int main()//主函数 
{
    freopen("cpp.in", "r", stdin);
    freopen("cpp.out", "w", stdout);
    scanf("%lld%lld",&m,&n);
    for(int i=1;i<=n;i++)
        scanf("%lld",&a[i]);
    sort(a+1,a+n+1,cmp);//先降幂排一下序 
    maxx=a[1];//将最大值赋成输入中 n 个孩子的最大期望值 
    while(m)//循环找出最优分配方法 
        if(a[qwq]!=maxx) 
            maxx=a[1],qwq=1;
        else  
            a[qwq++]--,m--;
    for(int i=1;i<=n;i++)
        ans+=a[i]*a[i];//将少的颗数平方累加到最优方案里,注意这道题最后一个点成功把 STL math 库里的 pow 函数完美地卡死了 
    printf("%lld",ans);
    return 0;
}

AC代码2

#include <iostream>
#include <cstdio>
#include <algorithm>
#define SIZE (int)1e5 + 10
#define ll long long
using namespace std;
ll a[SIZE];

bool cmp(ll, ll);

int main() {
	freopen("cpp.in", "r", stdin);
	freopen("cpp.out", "w", stdout);
	ll m, n;
	scanf("%lld%lld", &m, &n);
	for (int i = 1; i <= n; ++i) {
		scanf("%lld", &a[i]);
	}
	sort(a + 1, a + n + 1, cmp);
	int now = a[1];
	a[0] = 1;
	while (m) {
		if (a[a[0]] != now) {
			a[0] = 1;
			now = a[1];
		} else {
			--a[a[0]++];
			--m;
		}
	}
	ll ans = 0;
	for (int i = 1; i <= n; ++i) {
		ans += a[i] * a[i];
	}
	printf("%lld\n", ans); 
	return 0;
}

bool cmp(ll x, ll y) {
	return x > y;
}
发布了33 篇原创文章 · 获赞 0 · 访问量 167

猜你喜欢

转载自blog.csdn.net/weixin_42790071/article/details/105540024