背包问题和装载问题

背包问题描述:

有一个背包,能盛放的物品总重量为S,设有N件物品,其重量分别为w1,w2,…,wn,希看从N件物品中选择若干物品,所选物品的重量之和恰能放进该背包,即所选物品的重量之和即是S。

代码;

#include <iostream>
#include <stdlib.h>
using namespace std;
 
const int N = 7;//物品数量
const int S = 20;//能盛放的物品总重量
int w[N+1] = {0, 1, 4, 3, 4, 5, 2, 7};
 
int knap(int s,  int n)
{
	if(s == 0)
	{
		return 1;
	}
 
	if(s<0 || (s>0&&n<1))
	{
		return 0;
	}
 
	//第n个物品入选
	if(knap(s-w[n], n-1))
	{
		cout << w[n] << " ";
		return 1;
	}
 
	//第n个物品没入选
	return knap(s, n-1);    
}
 
int main(int argc, char *argv[])
{
	if(knap(S, N))
	{
		cout << endl << "OK" << endl;
	}
	else
	{
		cout << "NO" << endl;
	}
 
	system("PAUSE"); 
	return 0;
}
 

装载问题描述:

有两艘船,载重量分别是c1c2n个集装箱,重量是wi (i=1…n),且所有集装箱的总重量不超过c1+c2。确定是否有可能将所有集装箱全部装入两艘船。

思路:

(1) 首先将第一艘轮船尽可能装满;
(2) 将剩余的集装箱装上第二艘轮船。

关键代码:

int search(int m)
{	 
    int x,y;
    if(m>n)
        checkmax();	 
    else	 
    {
        a[m]=0;
        y=search(m+1); 
        if(cw+w[m]<=c1)
        {	 
            a[m]=1;
            cw=cw+w[m];
            x=search(m+1);
        }
    }	
}

完整代码:

#include<iostream>   
using namespace std;   
const int max(12);   
int c1,c2,n;   
int weight;   
int best;   
int boxw[max];   
void backtrack(int a)   
{   
    if(a==n)   
    {   
        if(weight>best)   
            best=weight;   
        return ;   
    }   
    if(weight+boxw[a]<=c1)   
    {   
        weight=weight+boxw[a];   
        backtrack(a+1);   
        weight=weight-boxw[a];   
    }   
    backtrack(a+1);   
}          
int main()   
{   
    while(1)   
    {   
        int sum=0;   
        cin>>c1>>c2>>n;   
        if(c1==0&&c2==0&&n==0)   
            break;   
        for(int i=0;i<n;i++)   
        {   
            cin>>boxw[i];   
            sum+=boxw[i];   
        }   
        best=weight=0;   
        backtrack(0);   
        if(sum-best<=c2)   
            cout<<"Yes"<<endl;   
        else   
            cout<<"No"<<endl;   
    }   
    return 0;   
}  

猜你喜欢

转载自blog.csdn.net/zhao2018/article/details/82891792