Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

0-1 ปัญหาเป้ใน C?


กระเป๋าเป้คือกระเป๋า และปัญหาของเป้เกี่ยวข้องกับการนำสิ่งของเข้ากระเป๋าตามมูลค่าของสิ่งของ โดยมีเป้าหมายเพื่อเพิ่มมูลค่าสูงสุดภายในกระเป๋า ใน 0-1 Knapsack คุณสามารถใส่ไอเท็มหรือทิ้งมัน ไม่มีแนวคิดที่จะใส่บางส่วนของไอเท็มลงในเป้

ตัวอย่างปัญหา

Value of items = {20, 25,40}
Weights of items = {25, 20, 30}
Capacity of the bag = 50

การกระจายน้ำหนัก

25,20{1,2}
20,30 {2,3}
If we use {1,3} the weight will be above the max allowed value.
For {1,2} : weight= 20+25=45 Value = 20+25 = 45
For {2,3}: weight=20+30=50 Value = 25+40=65

ค่าสูงสุดคือ 65 ดังนั้นเราจะใส่ไอเทม 2 และ 3 ลงในเป้

โปรแกรมสำหรับปัญหา 0-1 เป้

#include<stdio.h>
int max(int a, int b) {
   if(a>b){
      return a;
   } else {
      return b;
   }
}
int knapsack(int W, int wt[], int val[], int n) {
   int i, w;
   int knap[n+1][W+1];
   for (i = 0; i <= n; i++) {
      for (w = 0; w <= W; w++) {
         if (i==0 || w==0)
            knap[i][w] = 0;
         else if (wt[i-1] <= w)
            knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]);
         else
            knap[i][w] = knap[i-1][w];
      }
   }
   return knap[n][W];
}
int main() {
   int val[] = {20, 25, 40};
   int wt[] = {25, 20, 30};
   int W = 50;
   int n = sizeof(val)/sizeof(val[0]);
   printf("The solution is : %d", knapsack(W, wt, val, n));
   return 0;
}

ผลลัพธ์

The solution is : 65