c - 编译c代码时出错

标签 c algorithm knapsack-problem branch-and-bound

以下使用分支定界法的 0/1 背包代码显示了错误:

<小时/>

第 15 行:“Item”无法启动参数声明。 第 15 行:) 预计。 对于函数绑定(bind)也观察到同样的情况。

    #include <stdio.h>
    #include<conio.h>
    typedef enum {false, true}bool;
    struct Item
    {
        float weight;
        int value;
    };

    struct Node
    {
        int level, profit, bound;
        float weight;
    };
    bool cmp(Item a, Item b)
    {
        double r1 = (double)a.value / a.weight;
        double r2 = (double)b.value / b.weight;
        return r1 > r2;
    }
    int bound(Node u, int n, int W, Item arr[])
    {
        if (u.weight >= W)
            return 0;
        int profit_bound = u.profit;
        int j = u.level + 1;
        int totweight = u.weight;

        while ((j < n) && (totweight + arr[j].weight <= W))
        {
            totweight    += arr[j].weight;
            profit_bound += arr[j].value;
            j++;
        }
        if (j < n)
            profit_bound += (W - totweight) * arr[j].value /
                                             arr[j].weight;

        return profit_bound;
    }
    int knapsack(int W, Item arr[], int n)
    {
        sort(arr, arr + n, cmp);

        queue<Node> Q;
        Node u, v;
        u.level = -1;
        u.profit = u.weight = 0;
        Q.push(u);
        int maxProfit = 0;
        while (!Q.empty())
        {
            u = Q.front();
            Q.pop();

            if (u.level == -1)
                v.level = 0;
            if (u.level == n-1)
                continue;

            v.level = u.level + 1;

            v.weight = u.weight + arr[v.level].weight;
            v.profit = u.profit + arr[v.level].value;

            if (v.weight <= W && v.profit > maxProfit)
                maxProfit = v.profit;
            v.bound = bound(v, n, W, arr);

            if (v.bound > maxProfit)
                Q.push(v);

            v.weight = u.weight;
            v.profit = u.profit;
            v.bound = bound(v, n, W, arr);
            if (v.bound > maxProfit)
                Q.push(v);
        }

        return maxProfit;
    }


    void main()
    {
        int W = 10;   // Weight of knapsack
        Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100},
                      {5, 95}, {3, 30}};
        int n = sizeof(arr) / sizeof(arr[0]);

        printf("Maximum possible profit =%d " ,knapsack(W, arr, n));

        getch();
    }

最佳答案

这是因为 ItemNode 的任何使用都需要 struct:

bool cmp(struct Item a, struct Item b)

等等..

关于c - 编译c代码时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43528031/

相关文章:

algorithm - 为期权定价实现快速傅里叶变换

c - 标识 : Is that a string?

c - C 中双指针递增

c - 使用指针在 argv1 中存储命令行参数时出错

algorithm - 棘手的编程问题,我无法理解

c - 背包问题记忆化输出错误的解决方案

c - 如何在 Windows 上链接和编译 Raylib?

c++ - 随机排列单链表的前 N ​​个元素

python - 使用python,找到总和尽可能接近另一个的数字组合

c - 如何在具有两个属性、每个属性的必要权重和最小总值的 3d 数组中实现背包算法?