您的位置:首页 > 其它

将长度为N的钢管截成长为n1,n2,n3各若干根,求所有可能的组合

2009-03-08 23:09 211 查看
题目来自CSDN论坛:

http://topic.csdn.net/u/20090308/21/4595b675-046c-46e1-8973-8995bd50af05.html?seed=1504879824

有一根钢管需要切割,有几种切割长度。求最省料的切割方法。
比如一根钢管3米,可以切割成0.2米、0.3米、0.4米三种。问怎么样的切割才不会浪费材料。每一种长度的都可以切割任意次。
可以0.2*15可以(0.2*2+0.3*2)*3可以0.3*10,怎么样组合都可以,求一共有多少种组合,要是没有不浪费的方法,那么用最省料的方法,会浪费多少。

//放大十倍,用整型来计算:

static void GetSplit(int totalLength, int[] length)
{
Array.Sort(length);//先排个序,可以减少循环的次数
int min = totalLength;//最小的被浪费长度
List<string> result = new List<string>();//保存最省料时各长度的数量
for (int i = 0; i <= (int)(totalLength / length[2]); i++)
{
for (int j = 0; j <= (int)(totalLength / length[1]); j++)
{
int tempSum = i * length[2] + j * length[1];//计算取前两种长度的数量后,被截去的长度
if (tempSum > totalLength) break;
int temp = (int)((totalLength - tempSum) / length[0]);//计算第三个长度能截出的数量
if (totalLength - tempSum - temp * length[0] < min)//检查是否有更省料的可能
{
min = totalLength - tempSum - temp * length[0];
result.Clear();
result.Add(temp + "," + j + "," + i);
}
else if (totalLength - tempSum - temp * length[0] == min)
{
result.Add(temp + "," + j + "," + i);
}
}
}
foreach (string s in result)//输出结果
Console.WriteLine(s);
}

static void Main(string[] args)
{
//GetSplit(3.0, new double[] {0.2,0.3,0.4 });
GetSplit(30, new int[] { 2, 3, 4 });
}

/*输出结果:(分别是0.2,0.3,0.4的取值)
15,0,0
12,2,0
9,4,0
6,6,0
3,8,0
0,10,0
13,0,1
10,2,1
7,4,1
4,6,1
1,8,1
11,0,2
8,2,2
5,4,2
2,6,2
9,0,3
6,2,3
3,4,3
0,6,3
7,0,4
4,2,4
1,4,4
5,0,5
2,2,5
3,0,6
0,2,6
1,0,7
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐