Backtracking algorithm to solve problems (C language)


foreword

Solve the problem:
Design the knapsack problem through the backtracking algorithm:
there are n items with weights {w1, w2, ..., wn}, and their values ​​are {v1, v2, ..., vn}, given a capacity W Backpack. Design a plan to select some items from these items and put them into the backpack. Each item is either selected or not selected. It is required that the selected items not only be able to be placed in the backpack, but also have the greatest value.
Find all solutions and the best solution when W=6 for the 4 items shown in the table below.

insert image description here


1. Experimental procedures and results

#include<stdio.h>
int weight[100];
int value[100];
int n,max_weight,max_value;
 
int best[100],tree[100];
void x(){
    
    
	printf("--------------------------------------------\n");
}
 
void s()
{
    
    
	int i,j,k,l;
	x();
	printf("所能选的最大价值是%d\n",max_value);
	printf("最佳选填方案为: ");
	for(i=1;i<=n;i++){
    
    
		if(best[i]==1)
			printf("\t选择第%d个",i);
		    printf("\n");
	}}
 
void foolish(int length,int allweight,int allvalue)
{
    
    
	if(length>=n+1)
	{
    
    
		if(allvalue>max_value)
		{
    
    
			int i;
			max_value = allvalue;
			for(i=1;i<=n;i++)
				best[i] = tree[i];
		}
	}
	else
	{
    
    
		if(allweight>=weight[length+1])
		{
    
    
			allweight = allweight - weight[length+1];
			allvalue = allvalue + value[length+1];
			tree[length+1] = 1;
			foolish(length+1,allweight,allvalue);
			tree[length+1] = 0;
			allweight = allweight + weight[length+1];
			allvalue = allvalue - value[length+1];
		}
		foolish(length+1,allweight,allvalue);
	}
}
 
void init()
{
    
    
	int i;
	max_value = 0;
	for(i=1;i<=n;i++)
		tree[i] = 0;
}
 
void main()
{
    
    
	int i,j,k,l;
	x();
	printf("请输入物品数量: ");
	scanf("%d",&n);
	printf("请输入背包容量: ");
	scanf("%d",&max_weight);
	x();
	{
    
    
		for(i=1;i<=n;i++)
			{
    
    printf("请输入第%d个物品质量: ",i);
		scanf("%d",&weight[i]);}
		x();
		for(j=1;j<=n;j++)
			{
    
    printf("请输入第%d个物品价值: ",j);
		scanf("%d",&value[j]);}
		init();
		foolish(0,max_weight,0);
		s();
		}
}

Experimental results:
insert image description here


Summarize

insert image description here

The difficulty of this experiment lies in how to prune. At the beginning, I only used pruning without backtracking, which caused the display results to be abnormal. Emmm backtracking is a small difficulty, and I need to learn by myself.

Guess you like

Origin blog.csdn.net/weixin_51759592/article/details/125783034