Party Lemonade(贪心)

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?

Input
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
Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.

Examples
Input
4 12
20 30 70 90
Output
150
Input
4 3
10000 1000 100 10
Output
10
Input
4 3
10 100 1000 10000
Output
30
Input
5 787787787
123456789 234567890 345678901 456789012 987654321
Output
44981600785557577
Note
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.
题目分析:
看到这个题真的很容易想到完全背包问题啊。不仔细看题真的发现不了什么区别,有一个最大的区别是这个题如果换成背包问题的话那么这个背包的容量最少为l,而不是最大了。这个还和平常那种按性价比排序的贪心有一个大的区别,就是瓶子不能分割啊。
不过这个题瓶子容量为2^i-1,这样就可以保证相邻的两个瓶子,后面的瓶子是前面瓶子的二倍。这就相当于第二个饮料买一瓶,那么第一个饮料就可以买两瓶,那么就可以比较一下是第二个饮料买一瓶划算,还是第一个饮料买两瓶划算,就可以提前预处理一下。如下:

for(int i=2;i<=n;i++)//从2开始(如果给c初始化为很大的数,也可以从1开始)
        c[i]=min(c[i-1]*2,c[i]);

那么再仔细想一想,其实这么处理到最后一个饮料的时候,最后一个饮料相比前几个,**他是最划算的。**所以我们就可以从最后一个饮料开始购买。
注意,因为这里购买的饮料可以大于l,所以,我们买完最后一瓶饮料之后,如果此时还剩余空间,可以考虑多买一瓶饮料,然后再和接下来要买的饮料作比较,看看怎么买最实惠。光说肯定有点难理解,细节看代码。

#include<iostream>
using namespace std;
typedef long long ll;
ll c[101];
int power(int a,int b)//快速幂,用来算容量的,不写这个也行。
{
    if(b==0) return 1;
    int temp=power(a,b/2);
    temp=temp*temp;
    if(b%2==1)
        temp*=a;
    return temp;
}
int main()
{
    int n,l;
    ll ans=4e18;//初始化为非常大的数
    cin>>n>>l;
    for(int i=1;i<=n;i++)
        cin>>c[i];
    for(int i=2;i<=n;i++)
        c[i]=min(c[i-1]*2,c[i]);//预处理
    int v,need;
    ll sum=0;
    for(int i=n;i>=1;i--)
    {
        v=power(2,i-1);//v=1<<(i-1)算出这瓶饮料的容量
        need=l/v;//算出这瓶饮料在不超范围内需要的最大瓶数
        sum+=(ll)need*c[i];//加上买饮料花费的钱
        l%=v;//算出有没有多余空间
        int m=0;
        if(l>0)
            m=c[i];//这是多余空间买一瓶饮料的钱数
        ans=min(ans,sum+m);//比较一下哪个值最优
    }
    cout<<ans;
    return 0;
}
发布了59 篇原创文章 · 获赞 58 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/amazingee/article/details/104674293