牛客网 【每日一题】5月28日题目精讲 Protecting the Flowers
鏈接:
文章目錄
- 題目描述
- 題意:
- 題解:
- 代碼:
題目描述
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
輸入
輸出
86題意:
n頭牛,將第i頭牛運回谷倉需要時間2*ti,在等待運輸過程中每分鐘吃di朵花,問怎么運輸牛才能讓花的損失最小?
題解:
貪心問題
有AB兩頭牛相鄰,
A牛:Ta,Da
B牛:Tb, Db
在運A牛時,B牛在等待,等待了Ta2的時長,每分鐘吃Db多花,一共吃了Ta2Db多花
同理,在運B牛時,A牛在等待,等待了Tb2的時長,每分鐘吃Da多花,一共吃了Tb2Da多花
當運輸A牛比運輸B牛更劃算時,
Ta2Db<Tb2Da
TaDb<TbDa
然后將牛按照這個排序,這個順序就是最佳順序,直接計算花的損失即可
代碼:
tot記錄一分鐘所有等待牛破壞花的數量
#include<bits/stdc++.h> const int maxn=1e5+3; using namespace std; struct node{int t,d; }a[maxn]; bool cmp(node x,node y){return x.t*y.d<x.d*y.t; } int main() {int n;cin>>n;long long sum=0;long long tot=0;for(int i=1;i<=n;i++){cin>>a[i].t>>a[i].d;tot+=a[i].d;}sort(a+1,a+n+1,cmp);for(int i=1;i<=n;i++){ // cout<<"tot="<<tot<<endl;sum+=(tot-a[i].d)*a[i].t*2;tot-=a[i].d;}cout<<sum;return 0; }總結
以上是生活随笔為你收集整理的牛客网 【每日一题】5月28日题目精讲 Protecting the Flowers的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net 怎么做计算器(asp简易
- 下一篇: 牛客网 【每日一题】5月29日 管道取珠