题解:B4350 [信息与未来 2025] 美味水果

· · 题解

解题思路

贪心

我们应该要先吃掉那些好吃程度大的水果,因为:

(x + \sqrt y) - (y + \sqrt x) = x - y - \sqrt x + \sqrt y = (x-y)-(\sqrt x - \sqrt y) (x-y)-(\sqrt x - \sqrt y) \ge 0 x + \sqrt y \ge y + \sqrt x

数学优化

我们写出的程序时间复杂度太高了,但是我们可以发现:

所以,当数字变成 1 时,我们可以直接退出循环。

上代码

#include<bits/stdc++.h>
using namespace std;
int f(int x,int days)//数字x开days次根号后会变成几?
{
    for(int i=1;i<=days;i++)//枚举
    {
        if(x==1)//优化:如果x=1,因为 $\sqrt 1=1$,所以不管之后再开多少次更好,都是1
        return x;
        x=sqrt(x);//开根号
    }
    return x;
}
const int N=100005;//数组大小
int n,a[N],ans;
bool cmp(int x,int y)//cmp函数
{
    return x>y;//从大到小
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    scanf("%d",&a[i]);//输入
    sort(a+1,a+1+n,cmp);//贪心思路:从大到小选
    for(int i=1;i<=n;i++)
    ans+=f(a[i],i-1);//统计答案
    printf("%d",ans);
    return 0;
}