关闭

求一组战力值最大算法

635人阅读 评论(0) 收藏 举报
分类:

在论述上看到此问题,觉得有点意思,写段代码 欢迎大家测试拍砖


http://bbs.csdn.net/topics/390656629?page=1#post-396237502

"一组卡牌,从中抽取12张牌,每张卡牌的属性有战力值和COST值,要求是12张牌加起来的战力值取大,但COST加起来必须小于一个定值,求这样的算法"


typedef struct _tagCard_t
{
  int iCost, iValue;  
  _tagCard_t()
  {
    iCost = iValue = 0;
  }
}CARD;

template <int NUM> struct CardSelct
{
  int bSelected[NUM];
  int iSelected;
  int iCost, iValue;  

  CardSelct()
  {
    memset(this, 0, sizeof(*this));
  }
  
  CardSelct(CardSelct &other)
  {
    operator = (other);
  }
 
  void operator = (CardSelct &other)
  {
    for(int i=0; i<NUM; i++)
      bSelected[i] = other.bSelected[i];
    iSelected = other.iSelected;
    iCost = other.iCost;
    iValue = other.iValue;
  }
};

template <int iTotalCard> 
 int Select(CardSelct<iTotalCard> &sel, int SelCardNum, CARD card[iTotalCard], int iMaxCost)
{
  ASSERT(iTotalCard >= SelCardNum);
  for(int i=0; i<iTotalCard; i++)
  { 
    if(sel.iSelected >= SelCardNum) //数量已经足够
      break;
    
    CARD *pNewCard = &card[i];
    if(sel.bSelected[i]) //已经被选中
      continue;
    
    //计算不包含此项的成本和价值    
    CardSelct<iTotalCard> unselThis = sel;
    unselThis.bSelected[i] = -1;//仅标记
    Select(unselThis, SelCardNum, card, iMaxCost);
    
    //计算选择此项的成本和价值
    CardSelct<iTotalCard> selThis = sel;
    selThis.iCost += pNewCard->iCost;
    selThis.iValue += pNewCard->iValue;
    if(selThis.iCost <= iMaxCost)
    {
      selThis.bSelected[i] = 1; //标记选中
      selThis.iSelected++; //选中数
      Select(selThis, SelCardNum, card, iMaxCost); 
    }
    
    if(selThis.iCost > iMaxCost //超成本
      ||(selThis.iValue < unselThis.iValue) //价值低
      ||(selThis.iValue==unselThis.iValue && selThis.iCost>unselThis.iCost) //价值相同但成本高
      || 0) //不选择此项
    {
      if(unselThis.iSelected > 0) //不选项也有效
      {
        sel = unselThis;
      }
    }
    else 
    {
      sel = selThis;    
    }    
  }
  
  return sel.iValue;
}

void testCard()
{
  //随机化数据
  short seed = (short)time(NULL);
  TRACE( _T("seed=%d\n"), seed);
  srand( seed );
  
  const int iCard=50; //50张卡
  const int iSelect=12; //选12张
  CARD card[iCard]; //卡
  int iMaxCost = rand(); //限最高成本
  
  //使用随机数填充卡成本和价值
  {    
    for(int i=0; i<iCard; i++)
    {
      card[i].iCost = rand();
      card[i].iValue = rand();   
    }
  }
  CardSelct <iCard> sel;
  Select(sel, iSelect, card, iMaxCost);
  
  //结果输出
  {
    TRACE(_T("Card= cost   value  sel(cost<%d)\r\n"), iMaxCost);
    for(int i=0; i<iCard; i++)
    {
      TRACE(_T(" %03d [%06d %06d %+d]\r\n"), 
        i, card[i].iCost, card[i].iValue, 
        sel.bSelected[i]);
    }
    TRACE(_T("Total[%06d %06d %02d]\r\n"), 
      sel.iCost, sel.iValue, sel.iSelected);
  }
}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:293732次
    • 积分:5138
    • 等级:
    • 排名:第5779名
    • 原创:183篇
    • 转载:0篇
    • 译文:2篇
    • 评论:114条
    最新评论