Day 21 算法笔记之算法初步4.4 贪心

目录

1.月饼

2.组个最小数


1.月饼

#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;

struct mooncake{
	int store;
	double all_price;
	double single_price;
}martix[1000];

bool cmp(mooncake a,mooncake b){
	return a.single_price>b.single_price;
}


int main(){
	
	int n,m;
	scanf("%d %d",&n,&m);
	
	for(int i=0;i<n;i++){
		scanf("%d",&martix[i].store);
	}
	
	for(int i=0;i<n;i++){
		scanf("%lf",&martix[i].all_price);
		martix[i].single_price = martix[i].all_price/martix[i].store;
	}
	
	sort(martix,martix+n,cmp);
	
	int pos = 0;
	double whole=0;
	
	while(m!=0){
		if(martix[pos].store<=m){
			m-=martix[pos].store;
			whole+=martix[pos].all_price;
			pos+=1;
		}else{
			whole+=martix[pos].single_price*m;
			m=0;
		}
	}
	
	printf("%.2f\n",whole);
	
	return 0;
}

2.组个最小数

#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;



int main(){
	
	int martix[14];
	
	int no;
	
	for(int i=0;i<10;i++){
		scanf("%d",&martix[i]);
	}
	
	for(int i=1;i<10;i++){
		if(martix[i]!=0){
			printf("%d",i);
			martix[i]--;
			break;
		}
	}
	
	for(int i=0;i<10;i++){
		for(int j=0;j<martix[i];j++){
			printf("%d",i);
		}
	}
	
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/aixiaoxiao13/article/details/120713116
今日推荐