XidianOJ 1087 浪漫的V8

题目描述

V8为了讨女朋友开心,给lx承包大活后面那个水塘。为了筹集资金,V8偷偷地溜进了一座古墓,发现在他面前有金光闪闪的若干小箱子,里面全都是金粉,作为横行于各种@#¥&场所的V8来说,辨别不同成色的金粉早已不在话下,很快,他就给这些金粉的价值做出了评估,可惜V8力气太小,只能带走V体积的金粉,现在告诉你这些小箱子的体积,和每个箱子里面金粉的价值,问V8最多能带走多少价值的金粉?

输入

多组数据
第一行一个T,表示数据组数
之后对于每组数据
第一行一个整数n(1<=n<=10^3),表示箱子的数量,
之后n行,每行两个整数v,w(0<v<=10^3,0<=w<=10^3),分别表示箱子的体积和里面金粉的价值。
最后一行一个整数V(0<=V<=10^3),表示V8能带走的最大体积。

输出

每组数据一行,每行一个浮点数,表示最大价值,保留小数点后四位。

答案的绝对误差不超过10^-4即判为正确。

--正文

第一次做special judge,不过题很简单

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

struct Box {
    double Value,Weight,ActualValue; 
};
struct Box box[1001];
int n;
bool cmp(struct Box b1,struct Box b2){
    if (fabs(b1.ActualValue-b2.ActualValue) < 1e-6)
        return (b1.Weight < b2.Weight);
    return (b1.ActualValue > b2.ActualValue);
} 

int main(){
    int time,T; scanf("%d",&T);
    for (time=1;time<=T;time++){
        scanf("%d",&n);
        int i;
        for (i=1;i<=n;i++){
            double v,w;
            scanf("%lf %lf",&v,&w);
            box[i].Value = w; box[i].Weight = v;
            box[i].ActualValue =  w / v;
        }
        sort(box+1,box+1+n,cmp);
        double res = 0;
        double V;
        scanf("%lf",&V);
        for (i=1;i<=n;i++){
            if (V >= box[i].Weight) {
                V = V - box[i].Weight;
                res += box[i].Value;
            }
            else {
                res += V*box[i].ActualValue;
                break;
            }
        }
        printf("%.4lf
",res);
    }
    
    return 0;
} 
原文地址:https://www.cnblogs.com/ToTOrz/p/6169632.html