DFS——背包问题

在这里插入图片描述

#include<stdio.h>
const int maxn = 30;
int n, V, maxValue = 0;
int w[maxn], c[maxn];

void DFS(int index, int sumW, int sumC)
{
    
    
	// 死胡同 
	if(index == n) return;
	
	// 岔路口 —— 不选
	DFS(index + 1, sumW, sumC);
	
	// 岔路口 —— 选
	if(sumW + w[index] <= V)   // 剪枝 
	{
    
    
	    if(sumC + c[index] >= maxValue) maxValue = sumC + c[index];
		DFS(index + 1, sumW + w[index], sumC + c[index]);	
	} 
}

int main()
{
    
    
	scanf("%d%d", &n, &V);
	for(int i = 0; i < n; i++)
	{
    
    
		scanf("%d", &w[i]);
	}
	for(int i = 0; i < n; i++)
	{
    
    
		scanf("%d", &c[i]);
	}
	DFS(0,0,0);
	printf("%d", maxValue);
	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/tian__si/article/details/113913989