do 和while和openjudge中的1797:金银岛
do 是和while 结合使用的,在C++中do...while循环语句使用格式如下:
do
{
循环体
}while( 条件)
do表示这个循环的开始,while表示这个循环的结尾,如果程序执行到while,当while里面的条件为真则继续从do开始循环运行,如果为假,则跳出循环执行while以下的语句。
openjudge中有这么一道题 第1797道
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
描述
某天KID利用飞行器飞到了一个金银岛上,上面有许多珍贵的金属,KID虽然更喜欢各种宝石的艺术品,可是也不拒绝这样珍贵的金属。但是他只带着一个口袋,
口袋至多只能装重量为w的物品。岛上金属有s个种类, 每种金属重量不同,分别为n
1
, n
2
, ... , n
s
,同时每个种类的金属总的价值也不同,分别为v
1
,v
2
, ..., v
s
。KID想一次带走价值尽可能多的金属,问他最多能带走价值多少的金属。注意到金属是可以被任意分割的,并且金属的价值和其重量成正比。输入第1行是测试数据的组数k,后面跟着k组输入。
每组测试数据占3行,第1行是一个正整数w (1 <= w <= 10000),表示口袋承重上限。第2行是一个正整数s (1 <= s <=100),表示金属种类。第3行有2s个正整数,分别为n
1
, v
1
, n
2
,v
2
, ... , n
s
, v
s
分别为第一种,第二种,...,第s种金属的总重量和总价值(1 <= n
i
<= 10000, 1 <= v
i
<= 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
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
本题可以直接用sort,也可以通过快排,但建议sort,因为比较好理解!
#include<iostream> #include<iomanip> #include<algorithm> #include<cmath> #include<cstdio> #include<cstdlib> #include<queue> #include<stack> #include<cstring> using namespace std; int k; int shubao,zhonglei; struct haosicheng{ int zongjiazhi,zongzhiliang; double danjia; }item[500]; double mycomp(const haosicheng &a,const haosicheng &b) { return a.danjia>b.danjia; } void init() { int k; scanf("%d",&k); for(int i=1;i<=k;i++) { scanf("%d",&shubao); scanf("%d",&zhonglei); for(int j=1;j<=zhonglei;j++) { scanf("%d%d",&item[j].zongzhiliang,&item[j].zongjiazhi); item[j].danjia=(double)item[j].zongjiazhi/(double)item[j].zongzhiliang; } sort(item+1,item+(zhonglei+1),mycomp); double worth=0; for(int i=1;i<=zhonglei;i++) { if(shubao>=item[i].zongzhiliang) { worth=worth+item[i].danjia*item[i].zongzhiliang; shubao=shubao-item[i].zongzhiliang; } else { worth=worth+item[i].danjia*shubao; shubao=shubao-shubao; } } printf("%.2lf\n", worth); } } int main() { init(); return 0; }