1. 程式人生 > >UvaLive 4863 Balloons(貪心)

UvaLive 4863 Balloons(貪心)

這樣的 給定 ons urn 們的 bool div clu truct

題意:

給定n個隊伍, 然後A房間有a個氣球, B房間有b個氣球, 然後給出每個隊伍所需要的氣球數量和到A B房間的距離, 求把氣球全部送到每個隊伍的最短距離.

分析:

在氣球充足的情況下, 那麽我們對於每個隊伍, 肯定是哪個房間近就取哪個房間的氣球。

但是題目中氣球的數目有限, 所以很有可能出現某個時刻第i個隊伍到A比較近, 但是A沒有氣球了, 只能去B拿的這種情況。這樣的損失就是他們的距離差。

所以猜想是先把到A和到B距離差較大的隊伍先滿足了, 這樣就能降低損失, 有這種貪心的思想應該就能求出答案了。

 1 #include <bits/stdc++.h>
 2 using namespace
std; 3 int n , a, b; 4 struct T{ 5 int ned, da,db, dif; 6 friend bool operator<(T a, T b){//重載小於號 在sort中這樣是降序 7 return a.dif > b.dif; 8 } 9 }; 10 T team[10007]; 11 int main(){ 12 while(scanf("%d %d %d", &n, &a, &b) && n){ 13 for(int i = 0; i < n ;i ++){
14 scanf("%d %d %d", &team[i].ned,&team[i].da,&team[i].db); 15 team[i].dif = abs(team[i].da-team[i].db); 16 } 17 sort(team,team+n);//按到a 到b的差距來排序 18 int sum = 0; 19 for(int i = 0; i < n;i++){ 20 int ned = team[i].ned; 21 if
(team[i].da < team[i].db){//如果 到a房間距離比到b房間短, 就先去a取, 沒有再去b取 22 int v = min(ned, a); 23 sum += v * team[i].da + (ned - v) * team[i].db; 24 a -= v; b -= (ned - v); 25 } 26 else{//如果 到b房間距離比到a房間短, 就先去b取, 沒有再去a取 27 int v = min(ned,b); 28 sum += v * team[i].db + (ned - v) * team[i].da; 29 b -= v; a -= (ned - v); 30 } 31 } 32 printf("%d\n", sum); 33 } 34 return 0; 35 }

UvaLive 4863 Balloons(貪心)