编辑代码

#include <stdio.h>

#define N 6

int w[] = {0, 6, 5, 4, 2, 1};
int v[] = {0, 5, 3, 5, 3, 2};
int x[N];
int n = 5, c = 10;
int SumWeight = 0;
int SumValue = 0;
int OptimalValue = 0;
int OptimalSolution[N];

void backtrack(int t)
{
    if (t > n)
    {
        if (SumValue > OptimalValue)
        {
            OptimalValue = SumValue;
            for (int i = 1; i <= n; ++i)
                OptimalSolution[i] = x[i];
        }
    }
    else
    {
        for (int i = 0; i <= 1; ++i)
        {
            x[t] = i;

            if (i == 0)
            {
                backtrack(t + 1);
            }
            else
            {
                if ((SumWeight + w[t]) <= c)
                {
                    SumWeight += w[t];
                    SumValue += v[t];
                    backtrack(t + 1);
                    SumWeight -= w[t];
                    SumValue -= v[t];
                }
            }
        }
    }
}

int main()
{
    backtrack(1);

    printf("最优价值是: %d\n", OptimalValue);
    printf("(");
    for (int i = 1; i <= n; i++)
        printf("%d ", OptimalSolution[i]);
    printf(")");

    return 0;
}