您的位置:首页 > 其它

九度考研机试教程 23-题目1435:迷瘴

2015-10-21 13:26 393 查看
//题目1435:迷瘴

/*思路分析:采用贪心思想,每次选择浓度最小的,并且满足条件:小于等于W%浓度。

之前这题我一直WA,错误在于精度问题。 输入整数是16,可能被double类型实际保存为15.999999999999999,也可能保存为16.0000000000001,

所以直接比较会得出前者小于后者的情况,但事实上这种不相等是由double的精度损失造成的。在判断两个浮点数是否“相等时”,

要使用if(fabs(a - b) < eps)

。其中,fabs为取绝对值函数,a,b为两个double类型的数,eps为一个很小的浮点数,常取1e-8。*/

#include <iostream>

#include <algorithm>

#include <math.h>

#include <stdio.h>

using namespace std;

int main()

{

int C;

int n,V,W;

int p[100];

cin>>C;

//if(n==0) break;

for(int i=0;i<C;i++)

{

cin>>n>>V>>W;

for(int j=0;j<n;j++)

{

cin>>p[j];

}

sort(p,p+n);

int ans_v=0;

double ans_p=0.00;

double dl=0.00;

int tmpvol=0;

double tmpdegree=0.00;

double tmp=(double)W/100;

for(int i=0;i<n;i++)

{

tmpvol+=V;

dl+=(double)p[i]/100*V;

tmpdegree=(double)dl/tmpvol;

if(tmpdegree<tmp||fabs(tmpdegree - tmp) < 1e-8)

{

ans_v=tmpvol;

ans_p=tmpdegree;

}

else

break;

}

printf("%d %.2lf\n",ans_v,ans_p);

}

return 0;

}

/*相同体积的溶液,浓度越大,混制出来w%浓度,体积越小。

所以需要对溶液浓度大小进行一个排序,如果浓度小,则优先选择。

首先声明初始浓度为p = 0,初始体积为allV = 0;

那么每次混合都需要判断当前的浓度是否大于w。

由于浓度可能是double类型的数据,判断起来容易出错,所以我们反向思考,将除以改成乘以。

遇到不同的问题,可以多方位的思考解决方式。*/

#include <stdio.h>

#include <algorithm>

using namespace std;

int c,n,v,w;

int i;

int main(){

while(scanf("%d",&c) != EOF){

while(c > 0){

c--;

scanf("%d %d %d",&n,&v,&w);

int *array = new int
;

for (i = 0; i < n; i++) {

scanf("%d",&array[i]);

}

sort(array,array+n);

int p = 0;

int allV = 0;

for (i = 0; i < n; i++) {

if ((p + array[i]) > (allV + 1) * w) {

break;

}

p += array[i];

allV ++;

}

if (allV == 0) {

printf("0 0.00\n");

}else {

printf("%d %.2f\n",allV*v, p*1.0/(100*allV));

}

}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: