码迷,mamicode.com
首页 > 其他好文 > 详细

装载问题

时间:2014-05-21 19:20:24      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   c   code   java   

装载问题同样也是递归回溯法的一个简单应用,用子集树表示解空间显然是最合适的。在递归回溯时,可以进行相应的剪枝。问题的解要满足两个条件:

1.首先将第一艘轮船尽可能装满

2.将剩余的集装箱装上第二艘轮船

由此可知,只要求出不超过第一艘轮船载重量c1的最大值,若总重量-c1<=c2则可以装上两艘船。

bubuko.com,布布扣
/*
* @author Panoss
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<ctime>
#include<stack>
#include<queue>
#include<list>
using namespace std;
#define DBG 1
#define fori(i,a,b) for(int i = (a); i < (b); i++)
#define forie(i,a,b) for(int i = (a); i <= (b); i++)
#define ford(i,a,b) for(int i = (a); i > (b); i++)
#define forde(i,a,b) for(int i = (a); i >= (b); i++)
#define forls(i,a,b,n) for(int i = (a); i != (b); i = n[i])
#define mset(a,v) memset(a, v, sizeof(a))
#define mcpy(a,b) memcpy(a, b, sizeof(a))
#define dout DBG && cerr << __LINE__ << " >>| "
#define checkv(x) dout << #x"=" << (x) << " | "<<endl
#define checka(array,a,b) if(DBG) { \
dout<<#array"[] | " << endl; forie(i,a,b) cerr <<"["<<i<<"]="<<array[i]<<" |"<<((i-(a)+1)%5?" ":"\n"); if(((b)-(a)+1)%5) cerr<<endl; }
#define redata(T, x) T x; cin >> x
#define MIN_LD -2147483648
#define MAX_LD 2147483647
#define MIN_LLD -9223372036854775808
#define MAX_LLD 9223372036854775807
#define MAX_INF 18446744073709551615
inline int reint() { int d; scanf("%d",&d); return d; }
inline long relong() { long l; scanf("%ld",&l); return l; }
inline char rechar() { scanf(" "); return getchar(); }
inline double redouble() { double d; scanf("%lf", &d); return d; }
inline string restring() { string s; cin>>s; return s; }

int c1, c2, n, W[15];

int current_weight, best_weight, residue_weight, total_weight;

void init()
{
  mset(W, 0);
  current_weight = 0;
  best_weight = 0;
  total_weight = 0;

}
void DFS(int depth) 
{
  if(depth > n)
  {
    best_weight = max(best_weight, current_weight);
    return ;
  }
  residue_weight -= W[depth];

  if(current_weight + W[depth] <= c1) //搜索左子树
  {
    current_weight += W[depth];
    DFS(depth + 1);
    current_weight -= W[depth]; //回溯时一定要改回来,因为状态不改变
  }

  if(current_weight + residue_weight > best_weight) //搜索右子树,注意剪枝
    DFS(depth+1);

  residue_weight += W[depth];
}
int main()
{
  //freopen("data.txt","r",stdin);

  while(scanf("%d%d%d",&c1,&c2,&n)==3&&(c1+c2+n))
  {
    init();
    forie(i,1,n)
    {
      scanf("%d",&W[i]);
      total_weight += W[i];
    }

    residue_weight = total_weight;

    DFS(1);

    if(total_weight - best_weight <= c2)
      cout << "Yes" << endl;
    else
      cout <<"No" << endl;
  }
  return 0;
}
bubuko.com,布布扣

 

 

装载问题,布布扣,bubuko.com

装载问题

标签:style   blog   class   c   code   java   

原文地址:http://www.cnblogs.com/Panoss/p/3740119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!