A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.
Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci roubles. The number of bottles of each type in the store can be considered infinite.
You want to buy at least L liters of lemonade. How many roubles do you have to spend?
The first line contains two integers n and L (1 ≤ n ≤ 30; 1 ≤ L ≤ 109) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 109) — the costs of bottles of different types.
Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.
4 12 20 30 70 90
150
4 3 10000 1000 100 10
10
4 3 10 100 1000 10000
30
5 787787787 123456789 234567890 345678901 456789012 987654321
44981600785557577
In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles.
In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles.
In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles.
这道题在比赛的时候没有想到。赛后看了大佬代码觉得这道题思想很好。因此整理了一下:
思路:首先当只有一升时,令c[0]是最优的,然后2升的时候,c[1]最优。以此类推。所以我c[i]中的就是i升最小的那一个。
#include <iostream>
using namespace std;
typedef long long ll;
int N, L;
ll C[32];
ll price(int l)
{
ll r = 0;
for (int i = 0; i < 31; i++)
{
if (l & (1<<i))
r += C[i];
}
return r;
}//比如10111,就是c[0]+c[1]+c[2]+c[4]
int main()
{
cin >> N >> L;
cin >> C[0];
for (int i = 1; i < N; i++)//依次比较找出当前位置性价比最高的那瓶的价格
{
cin >> C[i];
C[i] = min(C[i], 2*C[i-1]);
}
for (int i = N; i < 31; i++)
C[i] = 2*C[i-1];//为了满足后边的有值。因为很可能最后一瓶买很多很多。L很大很大
ll minc = 1000000000000000000LL;
do
{
minc = min(minc, price(L));
L += (L&-L);//右侧最小的那个1的位置加上一。表示两瓶可能比一瓶要便宜(或者这样理解,后边的0变成1只肯能够让价钱更高)
// cout<<L<<" "<<(L&-L)<<endl;
}
while(L > 0);爆int为负值停止
cout <<minc << endl;
}