0034算法笔记——【分支限界法】最优装载问题

       有一批共个集装箱要装上2艘载重量分别为C1和C2的轮船,其中集装箱i的重量为Wi,且装载问题要求确定是否有一个合理的装载方案可将这个集装箱装上这2艘轮船。如果有,找出一种装载方案。 

     容易证明:如果一个给定装载问题有解,则采用下面的策略可得到最优装载方案。 
     (1)首先将第一艘轮船尽可能装满;
     (2)将剩余的集装箱装上第二艘轮船。 

     1、队列式分支限界法求解

      在算法的循环体中,首先检测当前扩展结点的左儿子结点是否为可行结点。如果是则将其加入到活结点队列中。然后将其右儿子结点加入到活结点队列中(右儿子结点一定是可行结点)。2个儿子结点都产生后,当前扩展结点被舍弃。

     活结点队列中的队首元素被取出作为当前扩展结点,由于队列中每一层结点之后都有一个尾部标记-1,故在取队首元素时,活结点队列一定不空。当取出的元素是-1时,再判断当前队列是否为空。如果队列非空,则将尾部标记-1加入活结点队列,算法开始处理下一层的活结点。

     节点的左子树表示将此集装箱装上船,右子树表示不将此集装箱装上船。设bestw是当前最优解;ew是当前扩展结点所相应的重量;r是剩余集装箱的重量。则当ew+r<bestw时,可将其右子树剪去,因为此时若要船装最多集装箱,就应该把此箱装上船。另外,为了确保右子树成功剪枝,应该在算法每一次进入左子树的时候更新bestw的值。

     为了在算法结束后能方便地构造出与最优值相应的最优解,算法必须存储相应子集树中从活结点到根结点的路径。为此目的,可在每个结点处设置指向其父结点的指针,并设置左、右儿子标志。

     找到最优值后,可以根据parent回溯到根节点,找到最优解。

     算法具体代码实现如下:

     1、Queue.h

  1. #include<iostream>   
  2. using namespace std;  
  3.   
  4. template <class T>  
  5. class Queue  
  6. {  
  7.     public:  
  8.         Queue(int MaxQueueSize=50);  
  9.         ~Queue(){delete [] queue;}  
  10.         bool IsEmpty()const{return front==rear;}  
  11.         bool IsFull(){return ( (  (rear+1)  %MaxSize==front )?1:0);}  
  12.         T Top() const;  
  13.         T Last() const;  
  14.         Queue<T>& Add(const T& x);  
  15.         Queue<T>& AddLeft(const T& x);  
  16.         Queue<T>& Delete(T &x);  
  17.         void Output(ostream& out)const;  
  18.         int Length(){return (rear-front);}  
  19.     private:  
  20.         int front;  
  21.         int rear;  
  22.         int MaxSize;  
  23.         T *queue;  
  24. };  
  25.   
  26. template<class T>  
  27. Queue<T>::Queue(int MaxQueueSize)  
  28. {  
  29.     MaxSize=MaxQueueSize+1;  
  30.     queue=new T[MaxSize];  
  31.     front=rear=0;  
  32. }  
  33.   
  34. template<class T >  
  35. T Queue<T>::Top()const  
  36. {  
  37.     if(IsEmpty())  
  38.     {  
  39.         cout<<"queue:no element,no!"<<endl;  
  40.         return 0;  
  41.     }  
  42.     else return queue[(front+1) % MaxSize];  
  43. }  
  44.   
  45. template<class T>  
  46. T Queue<T> ::Last()const  
  47. {  
  48.     if(IsEmpty())  
  49.     {  
  50.         cout<<"queue:no element"<<endl;  
  51.         return 0;  
  52.     }  
  53.     else return queue[rear];  
  54. }  
  55.   
  56. template<class T>  
  57. Queue<T>&  Queue<T>::Add(const T& x)  
  58. {  
  59.     if(IsFull())cout<<"queue:no memory"<<endl;  
  60.     else  
  61.     {  
  62.         rear=(rear+1)% MaxSize;  
  63.         queue[rear]=x;  
  64.     }  
  65.     return *this;  
  66. }  
  67.   
  68. template<class T>  
  69. Queue<T>&  Queue<T>::AddLeft(const T& x)  
  70. {  
  71.     if(IsFull())cout<<"queue:no memory"<<endl;  
  72.     else  
  73.     {  
  74.         front=(front+MaxSize-1)% MaxSize;  
  75.         queue[(front+1)% MaxSize]=x;  
  76.     }  
  77.     return *this;  
  78. }  
  79.   
  80. template<class T>  
  81. Queue<T>&  Queue<T> ::Delete(T & x)  
  82. {  
  83.     if(IsEmpty())cout<<"queue:no element(delete)"<<endl;  
  84.     else   
  85.     {  
  86.         front=(front+1) % MaxSize;  
  87.         x=queue[front];  
  88.     }  
  89.     return *this;  
  90. }  
  91.   
  92.   
  93. template<class T>  
  94. void Queue <T>::Output(ostream& out)const  
  95. {  
  96.     for(int i=rear%MaxSize;i>=(front+1)%MaxSize;i--)  
  97.        out<<queue[i];  
  98. }  
  99.   
  100. template<class T>  
  101. ostream& operator << (ostream& out,const Queue<T>& x)  
  102. {x.Output(out);return out;}  
#include<iostream>
using namespace std;

template <class T>
class Queue
{
	public:
		Queue(int MaxQueueSize=50);
		~Queue(){delete [] queue;}
		bool IsEmpty()const{return front==rear;}
		bool IsFull(){return ( (  (rear+1)  %MaxSize==front )?1:0);}
		T Top() const;
		T Last() const;
		Queue<T>& Add(const T& x);
		Queue<T>& AddLeft(const T& x);
		Queue<T>& Delete(T &x);
		void Output(ostream& out)const;
		int Length(){return (rear-front);}
	private:
		int front;
		int rear;
		int MaxSize;
		T *queue;
};

template<class T>
Queue<T>::Queue(int MaxQueueSize)
{
	MaxSize=MaxQueueSize+1;
	queue=new T[MaxSize];
	front=rear=0;
}

template<class T >
T Queue<T>::Top()const
{
	if(IsEmpty())
	{
		cout<<"queue:no element,no!"<<endl;
		return 0;
	}
	else return queue[(front+1) % MaxSize];
}

template<class T>
T Queue<T> ::Last()const
{
	if(IsEmpty())
	{
		cout<<"queue:no element"<<endl;
		return 0;
	}
	else return queue[rear];
}

template<class T>
Queue<T>&  Queue<T>::Add(const T& x)
{
	if(IsFull())cout<<"queue:no memory"<<endl;
	else
	{
		rear=(rear+1)% MaxSize;
	    queue[rear]=x;
	}
	return *this;
}

template<class T>
Queue<T>&  Queue<T>::AddLeft(const T& x)
{
	if(IsFull())cout<<"queue:no memory"<<endl;
	else
	{
		front=(front+MaxSize-1)% MaxSize;
		queue[(front+1)% MaxSize]=x;
	}
	return *this;
}

template<class T>
Queue<T>&  Queue<T> ::Delete(T & x)
{
	if(IsEmpty())cout<<"queue:no element(delete)"<<endl;
	else 
	{
		front=(front+1) % MaxSize;
		x=queue[front];
	}
	return *this;
}


template<class T>
void Queue <T>::Output(ostream& out)const
{
	for(int i=rear%MaxSize;i>=(front+1)%MaxSize;i--)
	   out<<queue[i];
}

template<class T>
ostream& operator << (ostream& out,const Queue<T>& x)
{x.Output(out);return out;}
      2、 6d3-1.cpp

  1. //装载问题 队列式分支限界法求解    
  2. #include "stdafx.h"   
  3. #include "Queue.h"   
  4. #include <iostream>   
  5. using namespace std;  
  6.   
  7. const int N = 4;  
  8.   
  9. template<class Type>  
  10. class QNode  
  11. {  
  12.     template<class Type>  
  13.     friend void EnQueue(Queue<QNode<Type>*>&Q,Type wt,int i,int n,Type bestw,QNode<Type>*E,QNode<Type> *&bestE,int bestx[],bool ch);  
  14.   
  15.     template<class Type>  
  16.     friend Type MaxLoading(Type w[],Type c,int n,int bestx[]);  
  17.   
  18.     private:  
  19.         QNode *parent;  //指向父节点的指针  
  20.         bool LChild;    //左儿子标识  
  21.         Type weight;    //节点所相应的载重量  
  22. };  
  23.   
  24. template<class Type>  
  25. void EnQueue(Queue<QNode<Type>*>&Q,Type wt,int i,int n,Type bestw,QNode<Type>*E,QNode<Type> *&bestE,int bestx[],bool ch);  
  26.   
  27. template<class Type>  
  28. Type MaxLoading(Type w[],Type c,int n,int bestx[]);  
  29.   
  30. int main()  
  31. {  
  32.     float c = 70;    
  33.     float w[] = {0,20,10,26,15};//下标从1开始    
  34.     int x[N+1];    
  35.     float bestw;  
  36.     
  37.     cout<<"轮船载重为:"<<c<<endl;    
  38.     cout<<"待装物品的重量分别为:"<<endl;    
  39.     for(int i=1; i<=N; i++)    
  40.     {    
  41.         cout<<w[i]<<" ";    
  42.     }    
  43.     cout<<endl;    
  44.     bestw = MaxLoading(w,c,N,x);    
  45.     
  46.     cout<<"分支限界选择结果为:"<<endl;    
  47.     for(int i=1; i<=4; i++)    
  48.     {    
  49.         cout<<x[i]<<" ";    
  50.     }    
  51.     cout<<endl;    
  52.     cout<<"最优装载重量为:"<<bestw<<endl;  
  53.     
  54.     return 0;    
  55. }  
  56.   
  57. //将活节点加入到活节点队列Q中   
  58. template<class Type>  
  59. void EnQueue(Queue<QNode<Type>*>&Q,Type wt,int i,int n,Type bestw,QNode<Type>*E,QNode<Type> *&bestE,int bestx[],bool ch)  
  60. {  
  61.     if(i == n)//可行叶节点  
  62.     {  
  63.         if(wt == bestw)  
  64.         {  
  65.             //当前最优装载重量   
  66.             bestE = E;  
  67.             bestx[n] = ch;            
  68.         }  
  69.         return;  
  70.     }  
  71.     //非叶节点   
  72.     QNode<Type> *b;  
  73.     b = new QNode<Type>;  
  74.     b->weight = wt;  
  75.     b->parent = E;  
  76.     b->LChild = ch;  
  77.     Q.Add(b);  
  78. }  
  79.   
  80. template<class Type>  
  81. Type MaxLoading(Type w[],Type c,int n,int bestx[])  
  82. {//队列式分支限界法,返回最优装载重量,bestx返回最优解   
  83.  //初始化   
  84.     Queue<QNode<Type>*> Q;      //活节点队列   
  85.     Q.Add(0);                   //同层节点尾部标识  
  86.     int i = 1;                  //当前扩展节点所处的层  
  87.     Type Ew = 0,                //扩展节点所相应的载重量  
  88.          bestw = 0,             //当前最优装载重量  
  89.          r = 0;                 //剩余集装箱重量  
  90.   
  91.     for(int j=2; j<=n; j++)  
  92.     {  
  93.         r += w[j];  
  94.     }  
  95.       
  96.     QNode<Type> *E = 0,           //当前扩展节点  
  97.                 *bestE;         //当前最优扩展节点  
  98.   
  99.     //搜索子集空间树   
  100.     while(true)  
  101.     {  
  102.         //检查左儿子节点   
  103.         Type wt = Ew + w[i];  
  104.         if(wt <= c)//可行节点  
  105.         {  
  106.             if(wt>bestw)  
  107.             {  
  108.                 bestw = wt;  
  109.             }  
  110.             EnQueue(Q,wt,i,n,bestw,E,bestE,bestx,true);  
  111.         }  
  112.   
  113.         //检查右儿子节点   
  114.         if(Ew+r>bestw)  
  115.         {  
  116.             EnQueue(Q,Ew,i,n,bestw,E,bestE,bestx,false);  
  117.         }  
  118.         Q.Delete(E);//取下一扩展节点   
  119.   
  120.         if(!E)//同层节点尾部  
  121.         {  
  122.             if(Q.IsEmpty())  
  123.             {  
  124.                 break;  
  125.             }  
  126.             Q.Add(0);       //同层节点尾部标识   
  127.             Q.Delete(E);    //取下一扩展节点  
  128.             i++;            //进入下一层   
  129.             r-=w[i];        //剩余集装箱重量  
  130.         }  
  131.         Ew  =E->weight;      //新扩展节点所对应的载重量  
  132.     }  
  133.   
  134.     //构造当前最优解   
  135.     for(int j=n-1; j>0; j--)  
  136.     {  
  137.         bestx[j] = bestE->LChild;  
  138.         bestE = bestE->parent;  
  139.     }  
  140.     return bestw;  
  141. }  
//装载问题 队列式分支限界法求解 
#include "stdafx.h"
#include "Queue.h"
#include <iostream>
using namespace std;

const int N = 4;

template<class Type>
class QNode
{
	template<class Type>
	friend void EnQueue(Queue<QNode<Type>*>&Q,Type wt,int i,int n,Type bestw,QNode<Type>*E,QNode<Type> *&bestE,int bestx[],bool ch);

	template<class Type>
	friend Type MaxLoading(Type w[],Type c,int n,int bestx[]);

	private:
		QNode *parent;	//指向父节点的指针
		bool LChild;    //左儿子标识
		Type weight;    //节点所相应的载重量
};

template<class Type>
void EnQueue(Queue<QNode<Type>*>&Q,Type wt,int i,int n,Type bestw,QNode<Type>*E,QNode<Type> *&bestE,int bestx[],bool ch);

template<class Type>
Type MaxLoading(Type w[],Type c,int n,int bestx[]);

int main()
{
	float c = 70;  
    float w[] = {0,20,10,26,15};//下标从1开始  
    int x[N+1];  
	float bestw;
  
    cout<<"轮船载重为:"<<c<<endl;  
    cout<<"待装物品的重量分别为:"<<endl;  
    for(int i=1; i<=N; i++)  
    {  
        cout<<w[i]<<" ";  
    }  
    cout<<endl;  
    bestw = MaxLoading(w,c,N,x);  
  
    cout<<"分支限界选择结果为:"<<endl;  
    for(int i=1; i<=4; i++)  
    {  
        cout<<x[i]<<" ";  
    }  
    cout<<endl;  
	cout<<"最优装载重量为:"<<bestw<<endl;
  
    return 0;  
}

//将活节点加入到活节点队列Q中
template<class Type>
void EnQueue(Queue<QNode<Type>*>&Q,Type wt,int i,int n,Type bestw,QNode<Type>*E,QNode<Type> *&bestE,int bestx[],bool ch)
{
	if(i == n)//可行叶节点
	{
		if(wt == bestw)
		{
			//当前最优装载重量
			bestE = E;
			bestx[n] = ch;			
		}
		return;
	}
	//非叶节点
	QNode<Type> *b;
	b = new QNode<Type>;
	b->weight = wt;
	b->parent = E;
	b->LChild = ch;
	Q.Add(b);
}

template<class Type>
Type MaxLoading(Type w[],Type c,int n,int bestx[])
{//队列式分支限界法,返回最优装载重量,bestx返回最优解
 //初始化
	Queue<QNode<Type>*> Q;		//活节点队列
	Q.Add(0);					//同层节点尾部标识
	int i = 1;					//当前扩展节点所处的层
	Type Ew = 0,				//扩展节点所相应的载重量
		 bestw = 0,				//当前最优装载重量
		 r = 0;					//剩余集装箱重量

	for(int j=2; j<=n; j++)
	{
		r += w[j];
	}
	
	QNode<Type> *E = 0,			//当前扩展节点
				*bestE;			//当前最优扩展节点

	//搜索子集空间树
	while(true)
	{
		//检查左儿子节点
		Type wt = Ew + w[i];
		if(wt <= c)//可行节点
		{
			if(wt>bestw)
			{
				bestw = wt;
			}
			EnQueue(Q,wt,i,n,bestw,E,bestE,bestx,true);
		}

		//检查右儿子节点
		if(Ew+r>bestw)
		{
			EnQueue(Q,Ew,i,n,bestw,E,bestE,bestx,false);
		}
		Q.Delete(E);//取下一扩展节点

		if(!E)//同层节点尾部
		{
			if(Q.IsEmpty())
			{
				break;
			}
			Q.Add(0);       //同层节点尾部标识
			Q.Delete(E);	//取下一扩展节点
			i++;			//进入下一层
			r-=w[i];		//剩余集装箱重量
		}
		Ew  =E->weight;		//新扩展节点所对应的载重量
	}

	//构造当前最优解
	for(int j=n-1; j>0; j--)
	{
		bestx[j] = bestE->LChild;
		bestE = bestE->parent;
	}
	return bestw;
}
     程序运行结果如图:


     2、优先队列式分支限界法求解

      解装载问题的优先队列式分支限界法用最大优先队列存储活结点表。活结点x在优先队列中的优先级定义为从根结点到结点x的路径所相应的载重量再加上剩余集装箱的重量之和。
     优先队列中优先级最大的活结点成为下一个扩展结点。以结点x为根的子树中所有结点相应的路径的载重量不超过它的优先级。子集树中叶结点所相应的载重量与其优先级相同。
     在优先队列式分支限界法中,一旦有一个叶结点成为当前扩展结点,则可以断言该叶结点所相应的解即为最优解。此时可终止算法。

     算法具体代码实现如下:

     1、MaxHeap.h

  1. template<class T>  
  2. class MaxHeap  
  3. {  
  4.     public:  
  5.         MaxHeap(int MaxHeapSize = 10);  
  6.         ~MaxHeap() {delete [] heap;}  
  7.         int Size() const {return CurrentSize;}  
  8.   
  9.         T Max()   
  10.         {          //查   
  11.            if (CurrentSize == 0)  
  12.            {  
  13.                 throw OutOfBounds();  
  14.            }  
  15.            return heap[1];  
  16.         }  
  17.   
  18.         MaxHeap<T>& Insert(const T& x); //增  
  19.         MaxHeap<T>& DeleteMax(T& x);   //删  
  20.   
  21.         void Initialize(T a[], int size, int ArraySize);  
  22.   
  23.     private:  
  24.         int CurrentSize, MaxSize;  
  25.         T *heap;  // element array  
  26. };  
  27.   
  28. template<class T>  
  29. MaxHeap<T>::MaxHeap(int MaxHeapSize)  
  30. {// Max heap constructor.   
  31.     MaxSize = MaxHeapSize;  
  32.     heap = new T[MaxSize+1];  
  33.     CurrentSize = 0;  
  34. }  
  35.   
  36. template<class T>  
  37. MaxHeap<T>& MaxHeap<T>::Insert(const T& x)  
  38. {// Insert x into the max heap.   
  39.     if (CurrentSize == MaxSize)  
  40.     {  
  41.         cout<<"no space!"<<endl;   
  42.         return *this;   
  43.     }  
  44.   
  45.     // 寻找新元素x的位置   
  46.     // i——初始为新叶节点的位置,逐层向上,寻找最终位置   
  47.     int i = ++CurrentSize;  
  48.     while (i != 1 && x > heap[i/2])  
  49.     {  
  50.         // i不是根节点,且其值大于父节点的值,需要继续调整   
  51.         heap[i] = heap[i/2]; // 父节点下降  
  52.         i /= 2;              // 继续向上,搜寻正确位置  
  53.     }  
  54.   
  55.    heap[i] = x;  
  56.    return *this;  
  57. }  
  58.   
  59. template<class T>  
  60. MaxHeap<T>& MaxHeap<T>::DeleteMax(T& x)  
  61. {// Set x to max element and delete max element from heap.  
  62.     // check if heap is empty   
  63.     if (CurrentSize == 0)  
  64.     {  
  65.         cout<<"Empty heap!"<<endl;   
  66.         return *this;   
  67.     }  
  68.   
  69.     x = heap[1]; // 删除最大元素   
  70.     // 重整堆   
  71.     T y = heap[CurrentSize--]; // 取最后一个节点,从根开始重整  
  72.   
  73.     // find place for y starting at root  
  74.     int i = 1,  // current node of heap  
  75.        ci = 2; // child of i   
  76.   
  77.     while (ci <= CurrentSize)   
  78.     {  
  79.         // 使ci指向i的两个孩子中较大者   
  80.         if (ci < CurrentSize && heap[ci] < heap[ci+1])  
  81.         {  
  82.             ci++;  
  83.         }  
  84.         // y的值大于等于孩子节点吗?   
  85.         if (y >= heap[ci])  
  86.         {  
  87.             break;   // 是,i就是y的正确位置,退出  
  88.         }  
  89.   
  90.         // 否,需要继续向下,重整堆   
  91.         heap[i] = heap[ci]; // 大于父节点的孩子节点上升  
  92.         i = ci;             // 向下一层,继续搜索正确位置  
  93.         ci *= 2;  
  94.     }  
  95.   
  96.     heap[i] = y;  
  97.     return *this;  
  98. }  
  99.   
  100. template<class T>  
  101. void MaxHeap<T>::Initialize(T a[], int size,int ArraySize)  
  102. {// Initialize max heap to array a.   
  103.     delete [] heap;  
  104.     heap = a;  
  105.     CurrentSize = size;  
  106.     MaxSize = ArraySize;  
  107.   
  108.     // 从最后一个内部节点开始,一直到根,对每个子树进行堆重整   
  109.    for (int i = CurrentSize/2; i >= 1; i--)  
  110.    {  
  111.         T y = heap[i]; // 子树根节点元素  
  112.         // find place to put y   
  113.         int c = 2*i; // parent of c is target  
  114.                    // location for y   
  115.         while (c <= CurrentSize)   
  116.         {  
  117.             // heap[c] should be larger sibling  
  118.             if (c < CurrentSize && heap[c] < heap[c+1])  
  119.             {  
  120.                 c++;  
  121.             }  
  122.             // can we put y in heap[c/2]?   
  123.             if (y >= heap[c])  
  124.             {  
  125.                 break;  // yes  
  126.             }  
  127.   
  128.             // no   
  129.             heap[c/2] = heap[c]; // move child up  
  130.             c *= 2; // move down a level   
  131.         }  
  132.         heap[c/2] = y;  
  133.     }  
  134. }  
template<class T>
class MaxHeap
{
	public:
		MaxHeap(int MaxHeapSize = 10);
		~MaxHeap() {delete [] heap;}
        int Size() const {return CurrentSize;}

        T Max() 
		{          //查
           if (CurrentSize == 0)
		   {
                throw OutOfBounds();
		   }
           return heap[1];
        }

		MaxHeap<T>& Insert(const T& x); //增
		MaxHeap<T>& DeleteMax(T& x);   //删

		void Initialize(T a[], int size, int ArraySize);

	private:
		int CurrentSize, MaxSize;
		T *heap;  // element array
};

template<class T>
MaxHeap<T>::MaxHeap(int MaxHeapSize)
{// Max heap constructor.
	MaxSize = MaxHeapSize;
	heap = new T[MaxSize+1];
	CurrentSize = 0;
}

template<class T>
MaxHeap<T>& MaxHeap<T>::Insert(const T& x)
{// Insert x into the max heap.
	if (CurrentSize == MaxSize)
	{
		cout<<"no space!"<<endl; 
		return *this; 
	}

    // 寻找新元素x的位置
    // i——初始为新叶节点的位置,逐层向上,寻找最终位置
	int i = ++CurrentSize;
	while (i != 1 && x > heap[i/2])
	{
		// i不是根节点,且其值大于父节点的值,需要继续调整
		heap[i] = heap[i/2]; // 父节点下降
		i /= 2;              // 继续向上,搜寻正确位置
    }

   heap[i] = x;
   return *this;
}

template<class T>
MaxHeap<T>& MaxHeap<T>::DeleteMax(T& x)
{// Set x to max element and delete max element from heap.
	// check if heap is empty
	if (CurrentSize == 0)
	{
		cout<<"Empty heap!"<<endl; 
		return *this; 
	}

	x = heap[1]; // 删除最大元素
	// 重整堆
	T y = heap[CurrentSize--]; // 取最后一个节点,从根开始重整

	// find place for y starting at root
	int i = 1,  // current node of heap
	   ci = 2; // child of i

	while (ci <= CurrentSize) 
    {
		// 使ci指向i的两个孩子中较大者
		if (ci < CurrentSize && heap[ci] < heap[ci+1])
		{
			ci++;
		}
		// y的值大于等于孩子节点吗?
		if (y >= heap[ci])
		{
			break;   // 是,i就是y的正确位置,退出
		}

		// 否,需要继续向下,重整堆
		heap[i] = heap[ci]; // 大于父节点的孩子节点上升
		i = ci;             // 向下一层,继续搜索正确位置
		ci *= 2;
    }

	heap[i] = y;
	return *this;
}

template<class T>
void MaxHeap<T>::Initialize(T a[], int size,int ArraySize)
{// Initialize max heap to array a.
	delete [] heap;
	heap = a;
	CurrentSize = size;
	MaxSize = ArraySize;

	// 从最后一个内部节点开始,一直到根,对每个子树进行堆重整
   for (int i = CurrentSize/2; i >= 1; i--)
   {
		T y = heap[i]; // 子树根节点元素
		// find place to put y
		int c = 2*i; // parent of c is target
                   // location for y
		while (c <= CurrentSize) 
		{
			// heap[c] should be larger sibling
			if (c < CurrentSize && heap[c] < heap[c+1])
			{
				c++;
			}
			// can we put y in heap[c/2]?
			if (y >= heap[c])
			{
				break;  // yes
			}

			// no
			heap[c/2] = heap[c]; // move child up
			c *= 2; // move down a level
        }
		heap[c/2] = y;
	}
}
     2、6d3-2.cpp

  1. //装载问题 优先队列式分支限界法求解    
  2. #include "stdafx.h"   
  3. #include "MaxHeap.h"   
  4. #include <iostream>   
  5. using namespace std;  
  6.   
  7. const int N = 4;  
  8.   
  9. class bbnode;  
  10.   
  11. template<class Type>  
  12. class HeapNode  
  13. {  
  14.     template<class Type>  
  15.     friend void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev);  
  16.     template<class Type>  
  17.     friend Type MaxLoading(Type w[],Type c,int n,int bestx[]);  
  18.     public:  
  19.         operator Type() const{return uweight;}  
  20.     private:  
  21.         bbnode *ptr;        //指向活节点在子集树中相应节点的指针  
  22.         Type uweight;       //活节点优先级(上界)   
  23.         int level;          //活节点在子集树中所处的层序号  
  24. };  
  25.   
  26. class bbnode  
  27. {  
  28.     template<class Type>  
  29.     friend void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev);  
  30.     template<class Type>  
  31.     friend Type MaxLoading(Type w[],Type c,int n,int bestx[]);  
  32.     friend class AdjacencyGraph;  
  33.   
  34.     private:  
  35.         bbnode *parent;     //指向父节点的指针  
  36.         bool LChild;        //左儿子节点标识  
  37. };  
  38.   
  39. template<class Type>  
  40. void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev);  
  41.   
  42. template<class Type>  
  43. Type MaxLoading(Type w[],Type c,int n,int bestx[]);  
  44.   
  45.   
  46. int main()  
  47. {  
  48.     float c = 70;    
  49.     float w[] = {0,20,10,26,15};//下标从1开始    
  50.     int x[N+1];    
  51.     float bestw;  
  52.     
  53.     cout<<"轮船载重为:"<<c<<endl;    
  54.     cout<<"待装物品的重量分别为:"<<endl;    
  55.     for(int i=1; i<=N; i++)    
  56.     {    
  57.         cout<<w[i]<<" ";    
  58.     }    
  59.     cout<<endl;    
  60.     bestw = MaxLoading(w,c,N,x);    
  61.     
  62.     cout<<"分支限界选择结果为:"<<endl;    
  63.     for(int i=1; i<=4; i++)    
  64.     {    
  65.         cout<<x[i]<<" ";    
  66.     }    
  67.     cout<<endl;    
  68.     cout<<"最优装载重量为:"<<bestw<<endl;  
  69.     
  70.     return 0;   
  71. }  
  72.   
  73. //将活节点加入到表示活节点优先队列的最大堆H中   
  74. template<class Type>  
  75. void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev)  
  76. {  
  77.     bbnode *b = new bbnode;  
  78.     b->parent = E;  
  79.     b->LChild = ch;  
  80.     HeapNode<Type> N;  
  81.   
  82.     N.uweight = wt;  
  83.     N.level = lev;  
  84.     N.ptr = b;  
  85.     H.Insert(N);  
  86. }  
  87.   
  88. //优先队列式分支限界法,返回最优载重量,bestx返回最优解   
  89. template<class Type>  
  90. Type MaxLoading(Type w[],Type c,int n,int bestx[])  
  91. {  
  92.     //定义最大的容量为1000   
  93.     MaxHeap<HeapNode<Type>> H(1000);  
  94.   
  95.     //定义剩余容量数组   
  96.     Type *r = new Type[n+1];  
  97.     r[n] = 0;  
  98.   
  99.     for(int j=n-1; j>0; j--)  
  100.     {  
  101.         r[j] = r[j+1] + w[j+1];  
  102.     }  
  103.   
  104.     //初始化   
  105.     int i = 1;//当前扩展节点所处的层  
  106.     bbnode *E = 0;//当前扩展节点   
  107.     Type Ew = 0; //扩展节点所相应的载重量  
  108.   
  109.     //搜索子集空间树   
  110.     while(i!=n+1)//非叶子节点  
  111.     {  
  112.         //检查当前扩展节点的儿子节点   
  113.         if(Ew+w[i]<=c)  
  114.         {  
  115.             AddLiveNode(H,E,Ew+w[i]+r[i],true,i+1);  
  116.         }  
  117.         //右儿子节点   
  118.         AddLiveNode(H,E,Ew+r[i],false,i+1);  
  119.   
  120.         //取下一扩展节点   
  121.         HeapNode<Type> N;  
  122.         H.DeleteMax(N);//非空   
  123.         i = N.level;  
  124.         E = N.ptr;  
  125.         Ew = N.uweight - r[i-1];  
  126.     }  
  127.   
  128.     //构造当前最优解   
  129.     for(int j=n; j>0; j--)  
  130.     {  
  131.         bestx[j] = E->LChild;  
  132.         E = E->parent;  
  133.     }  
  134.   
  135.     return Ew;  
  136. }  
//装载问题 优先队列式分支限界法求解 
#include "stdafx.h"
#include "MaxHeap.h"
#include <iostream>
using namespace std;

const int N = 4;

class bbnode;

template<class Type>
class HeapNode
{
	template<class Type>
	friend void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev);
	template<class Type>
	friend Type MaxLoading(Type w[],Type c,int n,int bestx[]);
	public:
		operator Type() const{return uweight;}
	private:
		bbnode *ptr;		//指向活节点在子集树中相应节点的指针
		Type uweight;		//活节点优先级(上界)
		int level;			//活节点在子集树中所处的层序号
};

class bbnode
{
	template<class Type>
	friend void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev);
	template<class Type>
	friend Type MaxLoading(Type w[],Type c,int n,int bestx[]);
	friend class AdjacencyGraph;

	private:
		bbnode *parent;		//指向父节点的指针
		bool LChild;		//左儿子节点标识
};

template<class Type>
void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev);

template<class Type>
Type MaxLoading(Type w[],Type c,int n,int bestx[]);


int main()
{
	float c = 70;  
    float w[] = {0,20,10,26,15};//下标从1开始  
    int x[N+1];  
	float bestw;
  
    cout<<"轮船载重为:"<<c<<endl;  
    cout<<"待装物品的重量分别为:"<<endl;  
    for(int i=1; i<=N; i++)  
    {  
        cout<<w[i]<<" ";  
    }  
    cout<<endl;  
    bestw = MaxLoading(w,c,N,x);  
  
    cout<<"分支限界选择结果为:"<<endl;  
    for(int i=1; i<=4; i++)  
    {  
        cout<<x[i]<<" ";  
    }  
    cout<<endl;  
	cout<<"最优装载重量为:"<<bestw<<endl;
  
    return 0; 
}

//将活节点加入到表示活节点优先队列的最大堆H中
template<class Type>
void AddLiveNode(MaxHeap<HeapNode<Type>>& H,bbnode *E,Type wt,bool ch,int lev)
{
	bbnode *b = new bbnode;
	b->parent = E;
	b->LChild = ch;
	HeapNode<Type> N;

	N.uweight = wt;
	N.level = lev;
	N.ptr = b;
	H.Insert(N);
}

//优先队列式分支限界法,返回最优载重量,bestx返回最优解
template<class Type>
Type MaxLoading(Type w[],Type c,int n,int bestx[])
{
	//定义最大的容量为1000
	MaxHeap<HeapNode<Type>> H(1000);

	//定义剩余容量数组
	Type *r = new Type[n+1];
	r[n] = 0;

	for(int j=n-1; j>0; j--)
	{
		r[j] = r[j+1] + w[j+1];
	}

	//初始化
	int i = 1;//当前扩展节点所处的层
	bbnode *E = 0;//当前扩展节点
	Type Ew = 0; //扩展节点所相应的载重量

	//搜索子集空间树
	while(i!=n+1)//非叶子节点
	{
		//检查当前扩展节点的儿子节点
		if(Ew+w[i]<=c)
		{
			AddLiveNode(H,E,Ew+w[i]+r[i],true,i+1);
		}
		//右儿子节点
		AddLiveNode(H,E,Ew+r[i],false,i+1);

		//取下一扩展节点
		HeapNode<Type> N;
		H.DeleteMax(N);//非空
		i = N.level;
		E = N.ptr;
		Ew = N.uweight - r[i-1];
	}

	//构造当前最优解
	for(int j=n; j>0; j--)
	{
		bestx[j] = E->LChild;
		E = E->parent;
	}

	return Ew;
}
     程序运行结果如图:


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值