|BZOJ 1634|贪心|[Usaco2007 Jan]Protecting the Flowers 护花

本文针对USACO2007JanSilver中的一道题目进行了解析,介绍了如何通过快速排序和贪心算法解决牛吃花的问题。文章详细展示了如何定义比较函数来确定最优顺序,并给出了完整的C++实现代码。

BZOJ 1634
Luogu 2878
from: USACO 2007 Jan Sliver(USACO刷题第11题)

刚开始naive的认为比较函数是第一关键字 d 第二关键字t,狂炸的我..

对于两头牛 a,b ,他们的先后顺序不影响其他牛吃花的个数
那么考虑
a b前面,那么吃的花为 2d[b]t[a]
b a前面,那么吃的花为 2d[a]t[b]
要使 a 在前面吃的花最少,必须满足d[b]t[a]<d[a]t[b]
那么放进快排比较函数里就行了,之后贪心

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
using namespace std;

const int MAXN = 100000 + 5;

struct data {
    int di, ti;
    bool operator < (const data &b) const {
        return ti*b.di < b.ti*di;
    }
}c[MAXN];
int n;
LL sum, tot;

void clear() {
    tot = sum = 0;
}
void init() {
    clear();
    for (int i=1;i<=n;i++) {
        scanf("%d%d", &c[i].ti, &c[i].di);
        sum += c[i].di;
    }
    sort(c+1, c+1+n);
}
void solve() {
    for (int i=1;i<=n;i++) {
        sum -= c[i].di;
        tot += sum*c[i].ti*2;
    }
    printf("%lld\n", tot);
}
int main() {
    #ifndef ONLINE_JUDGE
    freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
    #endif
    while (scanf("%d", &n)==1) init(), solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值