CodeForces-913C 派对柠檬水

原题链接:http://codeforces.com/problemset/problem/913/C

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

题目大意:你需要从n种酒中买到总和大于等于L毫升的酒,每种酒的数量是无限的,第i种酒有2 ^(i-1)毫升,问最少花费。

贪心,虽然大多都能看出来是贪心题,但能不能做出来真的是碰运气(可以忽略不计)。看了大佬的题解后的一些领悟。

解题思路:会有两种状态:
1.全买最便宜(每ml酒对应价格最低)的那种酒
2.尽量买最便宜的酒,剩余的买其他酒

如果最便宜的那种酒的容积没有超过L,那我们至少会买一瓶,如果最便宜的那种酒容积的x倍没有超过L,那我们至少会买x瓶,但全买最便宜的酒所花的钱不一定是最少的,我们可以尽量买最便宜的酒,剩余的买其他酒,以此类推。(可能还是没说明白),看代码然后与第一个样例进行比对应该就差不多了。

然后两种情况进行对比。

Code:

#include<iostream>
#include<algorithm>
#include<cmath>

using namespace std;
typedef long long ll;
const int N = 350;
int c[N];

struct node {
	ll price;//酒的价格
	ll ml;//酒的毫升数
	double getprice;//单价 
};
node tt[N];

bool cmp(node a,node b){
	return a.getprice<b.getprice;
}

int main(){
	int n;
	ll L;
	cin>>n>>L;
	for(int i=1;i<=n;i++){
		cin>>tt[i].price;
		tt[i].ml=(1LL<<(i-1));//位运算,可以当做pow(2,i-1)来理解 
		tt[i].getprice=1.0*tt[i].price/tt[i].ml;
	} 
	sort(tt+1,tt+n+1,cmp);
	ll res1=0,res2=0;
	ll ans=0x3f3f3f3f3f3f3f3f;//初始化为无限大 
	while(L>0){
		for(int i=1;i<=n;i++){//当i=2时,2所对应的酒就是当下最便宜的 ,以此类推,直到L<=0 
			//剩余的L ml酒全买这一种 
			res1=res2+ceil(1.0*L/tt[i].ml)*tt[i].price;
			ans=min(ans,res1);
			// 尽量买这一种,然后剩余的买其他的 
			res2+=L/tt[i].ml*tt[i].price;
			L-=tt[i].ml*(L/tt[i].ml);
			if(L<=0) break; 
		}
	}
//	cout<<ans1<<" "<<ans2<<endl; 
	ans=min(ans,res2);
	cout<<ans<<endl;
	
	return 0;
}
七月在野,八月在宇,九月在户,十月蟋蟀入我床下
原文地址:https://www.cnblogs.com/voids5/p/12695018.html