信息学奥赛一本通C++语言——1225:金银岛
【题目描述】 某天KID利用飞行器飞到了一个金银岛上,上面有许多珍贵的金属,KID虽然更喜欢各种宝石的艺术品,可是也不拒绝这样珍贵的金属。但是他只带着一个口袋,口袋至多只能装重量为w的物品。岛上金属有s个种类, 每种金属重量不同,分别为n1,n2,…,ns,同时每个种类的金属总的价值也不同,分别为v1,v2,…,vs。KID想一次带走价值尽可能多的金属,问他最多能带走价值多少的金属。注意到金属是可以被任意分割的,并且金属的价值和其重量成正比。
【输入】 第1行是测试数据的组数k,后面跟着k组输入。
每组测试数据占3行,第1行是一个正整数w(1≤w≤10000),表示口袋承重上限。第2行是一个正整数s(1≤s≤100),表示金属种类。第3行有2s个正整数,分别为n1,v1,n2,v2,…,ns,vs分别为第一种,第二种,…,第s种金属的总重量和总价值(1≤ni≤10000,1≤vi≤10000)。
【输出】 k行,每行输出对应一个输入。输出应精确到小数点后2位。
【输入样例】 2 50 4 10 100 50 30 7 34 87 100 10000 5 1 43 43 323 35 45 43 54 87 43 【输出样例】 171.93 508.00 【源代码】
#include<iostream> #include<cstdio> #include<cstring> #include<iomanip> #include<algorithm> using namespace std; struct metal { //定义结构体,金属 int weight;//重量 int value;//价值 double price;//单价 } m[10010]; bool cmp(metal x,metal y) { return x.price>y.price; //按照单价从高到低排序 } int main() { int k,w,s;//题设数据: 组数k 口袋承重上限w 金属种类s int sum_weight=0;//背包 金属重量和sum_weight double sum_value=0.0;//背包 金属的价值和sum_value cin>>k; while(k>0) { memset(m,0,sizeof(m)); cin>>w>>s; for(int i=1; i<=s; i++) { cin>>m[i].weight>>m[i].value; m[i].price=(m[i].value*1.0)/m[i].weight; } sort(m+1,m+1+s,cmp);//对金属进行排序 起始地址m+1,结束地址m+1+s int n=1;//背包 第n种金属 while(sum_weight<w&&n<=s) { if(sum_weight+m[n].weight<=w) { //第n种金属可以全部拿 sum_weight+=m[n].weight; sum_value+=m[n].value; } else { //第n种金属只能拿一部分 sum_value+=m[n].price*(w-sum_weight); sum_weight=w;//已经拿到足够的重量的金属了 } n++; } cout<<fixed<<setprecision(2)<<sum_value<<endl; k--; } return 0; }