최근에 배낭 문제를 연구하고 구현하려고합니다. 따라서 배낭 값이 100이고 40, 60, 100 같은 특정 가중치와 같은 최적의 솔루션 아이디어를 이해하고 이해할 수 있습니다. 그런 다음 최적의 솔루션은 배낭 값을 채우거나 등가 적으로 100이됩니다. 나는 프로그래밍의 한 섹션에 머물렀고 튜토리얼을 사용하여 재귀를 시도했지만 이것이 실제로 어떻게 작동 하는지를 알 수 없었다. 제가 이해 한 것을 언급하자배낭 - 프로그래밍 중 섹션을 이해할 수 없습니다.
/*A function or method to determine the max number*/
int max(int a, int b)
{
return (a > b) ? a : b;
}
/*Knapsack function or method with parameters knapsack value - w, weights, amounts, number of elements*/
int Knapsack(int w, int weight[], int amt[], int n)
{
if(n == 0 || w == 0)
{
return 0;
}
if(weight[n - 1] > w) /*If the nth value is greater than the knapsack value, then there will no optimal solution*/
{
return Knapsack(w, weight, amt, n - 1);
}
else
{
return max(amt[n - 1] + Knapsack(w - weight[n - 1], weight, amt, n - 1), Knapsack(w, weight, amt, n - 1)); /*Stuck in this section - It returns perfect solution but unable to understand how it's working. Debugged not getting the answer as expected*/
}
}
int main(void)
{
int amt[3], weight[3], w, i, elements, n;
/*printf("Enter number of elements: ");
scanf("%d", &elements);*/
printf("Enter the weight and amount individually up to 3: ");
for(i = 0; i < 3; i++)
{
scanf("%d %d", &weight[i], &amt[i]);
}
printf("\nEnter the knapsack value: ");
scanf("%d", &w);
n = sizeof(amt)/sizeof(amt[0]);
printf("%d %d", Knapsack(w, weight, amt, n), n);
return 0;
}
사람이 이해 할 수없는 오전 프로그래밍에 대한 간단한 작업 절차에서 설명 할 시간이 있다면 감사하겠습니다. 심지어 동적 프로그래밍을 사용하려고합니다. 하지만 그것은 조용한 복잡한 것 같습니다. 이 배낭 문제를 연구하는 완벽한 솔루션입니다 : napsack에 대한
이 질문은 [Codereview?] (http://codereview.stackexchange.com/) –
@WeatherVane에 속해 있습니까? 주어진 코드 조각이 어떻게 작동하는지에 대한 설명을 요구하고 자신의 자신의 코드. –