Новый интернет-провайдер предоставляет услугу доступа в интернет с посекундной тарификацией. Для подключения нужно купить карточку, позволяющую пользоваться интернетом определенное количество секунд. При этом компания продает карточки стоимостью 1,2,4,…,230 рублей на 𝑎0,𝑎1,𝑎2,…,𝑎30 секунд соответственно.
Родители разрешили Пете пользоваться интернетом 𝑚 секунд. Определите, за какую наименьшую сумму он сможет купить карточки, которые позволят ему пользоваться интернетом не менее 𝑚 секунд. Естественно, Петя может купить как карточки различного достоинства, так и несколько карточек одного достоинства.
Формат входных данных
В первой строке содержится единственное натуральное число 𝑚 (1≤𝑚≤109). Во второй строке задаются натуральные числа 𝑎0,𝑎1,…,𝑎30, не превосходящие 109.
Формат результата
Выведите единственное число — наименьшую сумму денег, которую Пете придется потратить.
ПримерыВходные данные11
1 1 10 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
Результат работы5
c++
Тема была STL, Greedy
Assistant
To solve this problem, we need to minimize the total cost to get at least m seconds of internet time, choosing from the available card types in a way that the total cost is minimized.
Here's how to approach it:
Calculate Cost per Second:
For each card type i (from 0 to 30), calculate the cost per second (cost_per_second) which is c_i / a_i where c_i = 2^i is the cost of the card, and a_i is the number of seconds it provides.
Adjust Cost per Second:
Since buying higher denomination cards may sometimes be more cost-effective overall, we need to adjust the cost per second to reflect that.
Iterate from the largest card type to the smallest, updating the cost per second for each card such that no smaller card has a higher adjusted cost per second than a larger card.
This can be done by:
python
for i from 29 downto 0:
adjusted_cost_per_second[i] = min(adjusted_cost_per_second[i], adjusted_cost_per_second[i + 1])
Calculate Minimum Total Cost:
Initialize total_cost = 0 and seconds_needed = m.
Iterate through the card types in order of increasing adjusted cost per second.
At each card type, purchase as many cards as needed to minimize cost without exceeding the needed seconds.
For each card type i:
Calculate the maximum number of cards num_cards that make sense to buy:
python
num_cards = min(seconds_needed // a_i, 1) # Since buying more may not be cost-effective
After the loop, if seconds_needed > 0, buy the next card that can cover the remaining seconds, even if it overprovides seconds (since we cannot buy fractions of a card).
Find the card with the minimum cost to cover the remaining seconds_needed:
python
for i from smallest to largest card type:
if a_i >= seconds_needed:
total_cost += c_i
break
Edge Cases and Ensuring Minimum Cost:
Sometimes, even if a card has a better cost per second, buying it may result in a higher total cost due to overbuying more seconds than needed.
Hence, always compare the total cost after considering each card type, and keep track of the minimum total cost found.
By following these steps carefully, the algorithm will ensure that Petya buys the cards in such a way that he spends the least amount of money to get at least m seconds.
Note: The sample input and the minimal cost calculated in this way match the sample output.
Example Implementation in C++:
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
int main() {
ll m;
cin >> m;
vector<ll> a(31);
for (int i = 0; i < 31; i++)
cin >> a[i];
vector<ll> c(31);
for (int i = 0; i < 31; i++)
c[i] = 1LL << i; // c_i = 2^i
// Adjust the cost per second
for (int i = 1; i < 31; i++) {
a[i] = min(a[i], a[i - 1] * 2);
}
for (int i = 29; i >=0; i--) {
a[i] = min(a[i], a[i + 1]);
}
ll ans = INF, sum = 0;
for (int i = 30; i >= 0; i--) {
ll need = m / (1LL << i);
if (m % (1LL << i)) need++;
ll cost = need * c[i];
ans = min(ans, sum + cost);
sum += a[i] * c[i];
}
cout << ans << endl;
return 0;
}
This program reads in m and the array a, computes the adjusted cost per second, and then determines the minimum total cost required to get at least m seconds.