即使正确键入了答案,代码也会在“分数背包”问题中显示错误输出

问题描述

我正在为极客解决极客上称为分数背包的问题,​​但我不知道为什么它会为特定的测试用例提供错误输出。我找不到任何错误

// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

struct Item{
    int value;
    int weight;
};


 // } Driver Code Ends
//class implemented
/*
struct Item{
    int value;
    int weight;
};
*/

static bool compare(Item i1,Item i2)
{
    double v1=i1.value/i1.weight;
    double v2=i2.value/i2.weight;
    
    return v1>v2;
}
class Solution
{
    public:
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int W,Item arr[],int n)
    {
        // Your code here
        sort(arr,arr+n,compare);
        double ans=0.0;
        long long int i=0;
        while(i<n)
        {
            
            if(arr[i].weight<=W)
            {
                ans+=arr[i].value;
                W-=arr[i].weight;
            }
            else
            {
                double partialvalue=(double)((double)arr[i].value/(double)arr[i].weight)*(double)W;
                ans+=partialvalue;
                break;
            }
            i++;
        
        }
        return ans;
        
    }
        
};



// { Driver Code Starts.
int main()
{
    int t;
    //taking testcases
    cin>>t;
    cout<<setprecision(2)<<fixed;
    while(t--){
        //size of array and weight
        int n,W;
        cin>>n>>W;
        
        Item arr[n];
        //value and weight of each item
        for(int i=0;i<n;i++){
            cin>>arr[i].value>>arr[i].weight;
        }
        
        //function call
        Solution ob;
        cout<<ob.fractionalKnapsack(W,arr,n)<<endl;
    }
    return 0;
}  // } Driver Code Ends
     

结果: 错误的答案。 !!!错误答案

可能您的代码无法针对多个测试用例 (TC) 正常工作。

您的代码失败的第一个测试用例:

输入: 84 87 78 16 94 36 87 43 50 22 63 28 91 10 64 27 41 27 73 37 12 19 68 30 83 31 63 24 68 36 30 3 23 1 8 2 5 3 2 7 4 2 7 7 7 3 7 92 31 57 24 63 21 97 32 6 26 85 28 37 6 47 30 14 8 25 46 83 46 15 18 35 15 44 1 88 9 77 29 4 5 9 1 5 3 7 3 7 3 7 3 7 3 35 29 68 2 98 3 18 43 53 7 2 31 87 42 66 40 45 20 41 30 32 18 98 22 82 26 10 28 68 7 98 4 87 4 2 1 2 3 7 3 2 1 2 3 7 3 2 1 0 97 24 19 46 47 2 22 6 80 39 65 29 42 1 94 1 35 15

它的正确输出是: 1078.00

您的代码输出是: 1075.57

解决方法

您在比较函数中忘记了强制转换:

static bool compare(Item i1,Item i2)
{
    double v1=i1.value/i1.weight;
    double v2=i2.value/i2.weight;
    
    return v1>v2;
}

应该

static bool compare(Item i1,Item i2)
{
    double v1=(double)i1.value/(double)i1.weight;
    double v2=(double)i2.value/(double)i2.weight;
    
    return v1>v2;
}

可能还有其他问题,但这是一个跳出来的问题!