Enter the "Basic Training of Deep Search" and step into the palace of C++ algorithms (2)

Xiaohang started to answer the second question...


[Search and Backtracking Algorithm] Loading Problem (Standard IO)

Time limit: 1000 ms Space limit: 262144 KB Specific limits

Topic description:

There is a batch of n containers to be loaded onto a ship with a load capacity of c, in which the weight of container i is wi. Find an optimal loading solution to fill the ship as much as possible, that is, load as heavy a container as possible onto the ship without limiting the loading volume.

enter:

The first line contains 2 positive integers n and c. n is the number of containers, and c is the carrying capacity of the ship. There are n positive integers in the next line, indicating the weight of the container.

Output:

Output the calculated maximum loading weight

Sample input:

5 10
7 2 6 5 4

Sample output:

10

Data range restrictions:

n<=35,c<=1000

"Actually, this is a super simple backpack problem that can be solved using recursion." Xiaohang thought, "Create a temporary weight and a final weight, search for each number (selected or not), as long as the search result is greater than the final result, Just assign value.”

#include<iostream>
using namespace std;
int n,c,w[40],s;
void dfs(int x,int sx)//第x个物品,sx为临时重量
{
	if(x>n)
	{
		if(sx>s) s=sx;//赋值
		return;
	}
	else
	{
		if(sx+w[x]<=c)//如果装入此物品,还没超载的话……
		{
			dfs(x+1,sx+w[x]);//装入此物品,并搜索下一件物品
		}
		dfs(x+1,sx);//在不装入此物品的情况下,搜索下一件物品
	}
}
int main()
{
	cin>>n>>c;
	for(int i=1;i<=n;i++) cin>>w[i];
	dfs(1,0);
	cout<<s;//输出最终重量
}

       but. Xiaohang later learned that this seemingly simple procedure almost timed out. Unwilling to give in, he modified it:

#include<bits/stdc++.h>
using namespace std;
int n,c,w[40],s,b[40],ms=0;
void dg(int x)
{
	if(s>=c)
	{
		if(s==c)
		{
			printf("%d",s);
			exit(0);
		}
		s-=w[x-1];
		if(ms<s)
			ms=s;
		s+=w[x-1];
	}
	else if(x==n)
	{
		if(ms<s)
			ms=s;
	}
	else
	{
		s+=w[x];
		dg(x+1);
		s-=w[x];
		dg(x+1);
	}
	return;
}
int main()
{
	scanf("%d%d",&n,&c);
	for(int i=0;i<n;i++)
		scanf("%d",&w[i]);
	dg(0);
	printf("%d",ms);
	return 0;
} 

        In this way, the running time is shortened a lot , and the complexity is n ...


        After that, the next question came into view...

Guess you like

Origin blog.csdn.net/aliyonghang/article/details/122524026