您的位置:首页 > 其它

背包分组问题的解法讨论

2009-08-29 12:28 411 查看
还是喜欢看算法题。。因为算法很菜。。哈哈。

题目请参见: eaglet 背包分组问题的解法

也花了近两个小时吧, 凭着直觉做了一下, 大家给点意见. 直接贴代码了, 感觉还是比较清晰的, 一看就懂。好吧好吧,这么多人问。。加算法说明在最后。

[code] using System;

using System.Collections.Generic;


namespace BagQuest

{

 class Program

{

 /// <summary>

 /// main function

 /// </summary>

 /// <param name="args">arguments</param>

 static void Main(string[] args)

{

 int[] goods ={ 25, 15, 10, 3, 1, 5, 14, 16, 5, 6};

 int[] sizes ={ 35, 45, 20};

 var usedIndex = new int[goods.Length];


 var result = new List<int>[sizes.Length];


 var sortedGoods = SortFromBigToSmall(goods);

 var sortedSizes = SortFromBigToSmall(sizes);

 for (var sIndex = 0; sIndex < sortedSizes.Length - 1; sIndex++)

{

 var addHelper = 0;

 for (var i = 0; i < sortedGoods.Length; i++)

{

 if (usedIndex[i] != 1 && usedIndex[i] != 2 && sortedGoods[i] + addHelper <= sortedSizes[sIndex])

{

 usedIndex[i] = 1; // mark the index as used

 addHelper += sortedGoods[i];

}


 if (addHelper == sortedSizes[sIndex] || i == sortedGoods.Length - 1)

{

 result[sIndex] = MemoryTheResult(sIndex, ref usedIndex, goods);

 addHelper = 0;

 break;

}

}

}


 var maxResultIndex = result.Length - 1;

 result[maxResultIndex] = new List<int>();

 for (var i = 0; i < usedIndex.Length; i++)

{

 if (usedIndex[i] != 1 && usedIndex[i] != 2)

{

 result[maxResultIndex].Add(sortedGoods[i]);

}

}


 #region OUTPUT


 for (var sIndex = 0; sIndex < sortedSizes.Length; sIndex++)

{

 Console.Write("\n{0} : ", sortedSizes[sIndex]);

 for (int rIndex = 0; rIndex < result[sIndex].Count; rIndex++)

{

 Console.Write("{0} ", result[sIndex][rIndex]);

}

}

 Console.WriteLine();

 #endregion

}


 /// <summary>

 /// record the result to result array

 /// </summary>

 /// <param name="sIndex">the index of the result</param>

 /// <param name="usedIndex">draft result record</param>

 /// <param name="goods">the item source</param>

 /// <returns>a final result record</returns>

 private static List<int> MemoryTheResult(int sIndex, ref int[] usedIndex, int[] goods)

{

 var resultList = new List<int>();

 for (var i = 0; i < usedIndex.Length; i++)

{

 if (usedIndex[i] == 1)

{

 resultList.Add(goods[i]);

 usedIndex[i] = 2;

}

}

 return resultList;

}


 /// <summary>

 /// sort the array

 /// </summary>

 /// <param name="goods">item source</param>

 /// <returns>the sorted (big to small) item array </returns>

 private static int[] SortFromBigToSmall(int[] goods)

{

 for (int j = 0; j < goods.Length; j++)

{

 for (int i = 0; i < goods.Length; i++)

{

 if (goods[j] > goods[i])

{

 var temp = goods[j];

 goods[j] = goods[i];

 goods[i] = temp;

}

}

}


 return goods;

}

}

}

[/code]

大家感觉如何? 多拍砖哈。。。

算法说明:

先把“原料”按照从大到小排序,再把“包”从大到小排序

然后把原料从最大的开始累加,如果超过了包的大小,就跳过,累加下一个(下一个会更小),如果超过,就再跳过。。如此找到最接近的组合。

只需找两组,剩下的就是第三组。

大致如此。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: