P2878 [USACO07JAN]保护花朵Protecting the Flowers - 贪心

传送门

思路:

对于“找出一种最优排列顺序,使答案最优”的贪心题目,我们可以用“邻项交换”的方法去找出并证明贪心策略。

例如本题,我们假设有两头奶牛,其到达牛圈时间分别为Ti,Ti+1,每分钟吃掉的花朵数分别为Di,Di+1

有两种情况:

① 排列顺序为i  i+1 则两头牛吃掉的花朵数为 res1=2TiDi+1

② 排列顺序为i+1  i 则两头牛吃掉的花朵数为 res2=2Ti+1Di

 假设前一种方案是最优解,则res1<res2,即TiDi+1<Ti+1Di

这样我们就找到了一种贪心的排序方法。

其实可以对这个式子移项:Di/Ti>Di+1/Ti+1

这样按每天奶牛的吃花速度与到达牛圈的时间的比值从大到小排列就可以了。

注意:除法有精度问题,需用double存储变量,最后用%.lf输出去掉小数位。

AC Code:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100000+10;
typedef long long ll;
struct node{
    double d,t;
}a[N];
bool cmp(const node x,const node y){
    return (x.d/x.t)>(y.d/y.t);
}
double s[N];
int main(){
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%lf%lf",&a[i].t,&a[i].d);
    sort(a+1,a+n+1,cmp);
    for(int i=1;i<=n;i++) s[i]=s[i-1]+a[i].d;
    double ans=0;
    for(int i=1;i<=n;i++) {
        ans+=2*a[i].t*(s[n]-s[i]);
    }
    printf("%.lf",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Loi-Brilliant/p/9419531.html