问题描述
Vishnu博士正在一个小镇开设一家新的世界级医院,该医院旨在成为该市患者的首选。医院有N间带电视和不带电视的两种类型的房间,每天的费用分别为R1和R2。然而,根据他的经验,Vishnu博士知道全年的患者人数并不是恒定不变的,而是遵循一种规律。下式给出了一年中任何一天的患者人数:
Patients per day = (6 – M)2 + |D – 15|
where,
M: the number of month starting from 1 to 12
D: the date from 1 to 31
所有患者更喜欢没有电视室,因为它们更便宜,但只有在没有电视室的情况下才会选择有电视室。医院的第一年运营目标是收入。给定此目标以及N , R1和R2的值,您需要确定医院应购买的电视数量,以使其达到收入目标。假设医院于1月1日开始营业,则该年份为非year年。
例子:
Input: N = 20, R1 = 1500, R2 = 1000, target = 7000000
Output: 14
Explanation:
Using the formula:
The number of patients on 1st Jan will be 39, on 2nd Jan will be 38 and so on.
Considering there are only twenty rooms and rates of both type of rooms are 1500 and 1000 respectively.
Therefore, 14 TV sets are needed to get the revenue of 7119500 with 13 TV sets.
The total revenue will be less than 7000000.
Input: N = 10, R1 = 1000, R2 = 1500, target = 10000000
Output: 10
Explanation:
In the above example, the target will not be achieved, even by equipping all the rooms with TV.
Hence, the answer is 10 i.e., total number of rooms in the hospital.
方法:想法是遍历全年并每天产生收入。找出每个可能拥有电视的客房数量,第一年的收入。请按照以下步骤解决问题:
- 假设有电视的房间总数为tvs ,其中0≤tvs≤N 。
- 对于电视的每个数字,可以通过遍历每一天来找到第一年的收入。
- 上面的公式可用于查找每天的患者人数。假设np是当前的患者人数。
- 当前的患者人数np可以具有今天的患者人数或房间总数的值,以最小者为准。
- 如果患者数量少于没有电视的房间数量,那么今天的总收入将是np * R1,因为它很便宜。
- 否则,如果患者人数大于没有电视的房间,那么今天的总收入为:
(N – tvs)*R2 + (np – (N – tvs))*R1
- 将每天的收入添加到目标值中,并打印检查所有可能的组合后生成的最大目标值。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function that returns number of
// patient for a day in a month
int getPatients(int M, int D)
{
return ((6 - M) * (6 - M))
+ abs(D - 15);
}
// Function that count the TVs with
// given amount of revenue target
void countTVs(long long n, long long r1,
long long r2, long long target)
{
long long np, tvs, current_target;
// Days in each month
vector days = { 0, 31, 28, 31,
30, 31, 30, 31,
31, 30, 31, 30,
31 };
// Check all possible combinations
for (tvs = 0; tvs <= n; tvs++) {
// Stores the current target
current_target = 0;
for (int m = 1; m <= 12; m++) {
for (int d = 1;
d <= days[m]; d++) {
// Number of patients
// on day d of month m
np = getPatients(m, d);
// Patients cannot be
// exceed number of rooms
np = min(np, n);
// If the number of patient is
// <= count of rooms without tv
if (np <= n - tvs) {
// All patients will opt
// for rooms without tv
current_target += np * r2;
}
// Otherwise
else {
// Some will opt for
// rooms with tv and
// others without tv
current_target
+= ((n - tvs) * r2
+ ((np - (n - tvs))
* r1));
}
}
}
// If current target meets
// the required target
if (current_target >= target) {
break;
}
}
// Print the count of TVs
cout << min(tvs, n);
}
// Driver Code
int main()
{
long long N = 20, R1 = 1500;
long long R2 = 1000;
long long target = 7000000;
// Function Call
countTVs(N, R1, R2, target);
return 0;
}
14
时间复杂度: O(N * 365),其中N是给定的房间数。
辅助空间: O(1)