問題描述:
排隊抓娃娃,每個人抓到一個娃娃後離開,設每個人抓娃娃所花時間爲time,每個人等待的時間爲第i~i-1所用時間,第一個人等待的時間爲0。如果等待的時間超過抓到娃娃的所用時間,則這個人不開心。
給定一個序列爲每個人抓到娃娃的所用時間,求如何排列,使得不開心人數最少。
輸入第一行n個人,輸入第二行每個人所用時間
input:
4
1 2 3 5
output:
1
參考代碼如下:
#include <iostream>
#include <algorithm>
using namespace std;
int NoHappy(int num[], int n){
int* cost;
int* wait;
cost = new int[n];
wait = new int[n];
int count = 1; //統計最大開心人數
sort(num, num+n);
for(int i = 0; i < n; i++){
if(i == 0){
cost[i] = num[i];
wait[i] = 0;
}else{
wait[i] = wait[i-1] + cost[i-1];
for(int j = i; j < n; j++){
if((num[j] - wait[i]) >= 0){
cost[i] = num[j];
count++;
break;
}
}
}
}
int unhappy = n - count;
return unhappy;
}
int main()
{
int n, precost;
cin >> n;
int* cost;
cost = new int[n];
for(int i = 0; i < n; i++){
cin >> cost[i];
}
cout << NoHappy(cost,n);
}