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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章