Protecting the Flowers 牛客题解

Protecting the Flowers

题目链接:传送门

链接:https://ac.nowcoder.com/acm/problem/25043
来源:牛客网

Farmer John went to cut some wood and left N (2 ≤ N ≤ 100,000) cows eating the grass, as usual. When he returned, he found to his horror that the cluster of cows was in his garden eating his beautiful flowers. Wanting to minimize the subsequent damage, FJ decided to take immediate action and transport each cow back to its own barn.
Each cow i is at a location that is Ti minutes (1 ≤ Ti ≤ 2,000,000) away from its own barn. Furthermore, while waiting for transport, she destroys Di (1 ≤ Di ≤ 100) flowers per minute. No matter how hard he tries, FJ can only transport one cow at a time back to her barn. Moving cow i to its barn requires 2 × Ti minutes (Ti to get there and Ti to return). FJ starts at the flower patch, transports the cow to its barn, and then walks back to the flowers, taking no extra time to get to the next cow that needs transport.
Write a program to determine the order in which FJ should pick up the cows so that the total number of flowers destroyed is minimized.
输入描述:
Line 1: A single integer N
Lines 2…N+1: Each line contains two space-separated integers, Ti and Di, that describe a single cow’s characteristics
输出描述:
Line 1: A single integer that is the minimum number of destroyed flowers
示例1
输入
复制
6
3 1
2 5
2 3
3 2
4 1
1 6
输出
复制
86

题目大概意思:现在农夫有n头牛,本来关在牛棚里,但是现在跑到花圃里去糟蹋花去了。现在农夫要把牛赶回去,每头牛回去的时间是ti,然后单位时间内糟蹋的花是pi,让我们算一下把牛都赶回去的最少花消耗量。

解题思路:这道题一看就是很明显的贪心,但是我最开始的思路还是有点不够,首先我们肯定可以想到,把单位时间内花消耗量的牛牛先送回去,这样就是一个简单的排序,加上计算。但是这样有一个弊端,并且不够贪心,因为有的牛牛虽然他造的少,但是他走的久,所以我们需要更换他们的排序基准,这样我们才能够保证贪心的思路是正确的。所以我们可以计算他们的消耗和花费时间的占比,那么现在我们就可以用一个结构体来存花费的时间,消耗的花,占比。最后根据占比来排序。

用一个前缀和数组来存前n头牛需要造多少花,我们可以看到n的范围是1e5,如果嵌套for循环肯定是会TLE的。

还有就是注意他的时间是两趟,算上来回。

理论成立,实践开始:

#include <bits/stdc++.h>

#define hh "\n"
#define endl "\n"
#define sss(a) scanf("%d",&a)
#define ll long long
#define  int ll
#define ppp(a) printf("%lld\n",a)
#define sssc(a) scanf("%c",&a)
#define rep(i, a, b) for(int i=a;i<=b;i++)
#define per(i, a, b) for(int i=b;i>=a;i--)
#define mm(a, b) memset(a,b,sizeof(a))
using namespace std;
typedef pair<int, int> pii;
const int maxn = 1e6 + 11;
const int mod = 998244353;
const int INF = 0x3f3f3f3f;
struct node {
    int x, y;
    double k;
} a[maxn];

bool cmp(node a, node b) {
    return a.k < b.k;
}

int pre[maxn];

signed main() {
    int t;
    cin >> t;
    for (int i = 1; i <= t; i++) {
        cin >> a[i].x >> a[i].y;
        a[i].k = a[i].x * 1.0 / a[i].y * 1.0;

    }
    sort(a + 1, a + 1 + t, cmp);
//    for (int i = 1; i <= t; i++)
//        cout << a[i].x << " " << a[i].y << endl;
    int sum = 0;
    pre[1] = a[1].y;
    for (int i = 2; i <= t; i++) {
        pre[i]=pre[i-1]+a[i].y;
    }
    for(int i = 1; i <= t ; i++){
        sum += (pre[t] - pre[i]) * a[i].x * 2;
    }
    cout << sum << endl;
    return 0;
}

然后这道题就可以快乐AC了,祝大家做题愉快!

上一篇:Hdu4742-Pinball Game 3D(cdq分治+树状数组)


下一篇:FOC中坐标系和电角度的定义