C# 最小最长距离算法,实现中的问题
我正在尝试实现一种算法,它采用一条有几段距离的路线,以及有人有时间走这条路线的天数。算法应计算每天的最小最长距离 我已经问过数学,因为我需要帮助找到数学函数。在那里你可以找到一个更容易理解我意思的例子 我尝试实现建议的递归函数:C# 最小最长距离算法,实现中的问题,c#,algorithm,C#,Algorithm,我正在尝试实现一种算法,它采用一条有几段距离的路线,以及有人有时间走这条路线的天数。算法应计算每天的最小最长距离 我已经问过数学,因为我需要帮助找到数学函数。在那里你可以找到一个更容易理解我意思的例子 我尝试实现建议的递归函数: Md(e1,…,en) = min{Md(e1,…,e′n−1), max{M d−1(e1,…,en−1), en}} 其中,Md(e1,…,en)是所有分组中最长阶段的最小值,e1 en是距离,Md是第d天的函数,假设Md(e1,e2,…,en)=max{e1,…
Md(e1,…,en) = min{Md(e1,…,e′n−1), max{M d−1(e1,…,en−1), en}}
其中,Md(e1,…,en)
是所有分组中最长阶段的最小值,e1 en
是距离,Md
是第d
天的函数,假设Md(e1,e2,…,en)=max{e1,…,en}如果d≥n
我在这里尝试实现这一点:
private static int recursiveMin(int[] teilstrecken, int days)
{
List<int> tempList1 = new List<int>(teilstrecken);
int last = tempList1.Last();
tempList1.Remove(tempList1.Last());
int vorletzter = tempList1.Last();
List<int> tempList2 = new List<int>(teilstrecken);
tempList1.Remove(tempList1.Last());
tempList1.Add(last + vorletzter);
tempList2.Remove(tempList2.Last());
int[] array1 = tempList1.ToArray();
int[] array2 = tempList2.ToArray();
if (nEtappen >= teilstrecken.Length)
{
return array1.Max();
}
return Math.Min(recursiveMin(array1, days), Math.Max(recursiveMin(array2, days-1), last));
}
private static int recursiveMin(int[]teilstrecken,int天)
{
列表模板1=新列表(teilstrecken);
int last=templast1.last();
templast1.Remove(templast1.Last());
int vorletzter=templast1.Last();
列表模板2=新列表(teilstrecken);
templast1.Remove(templast1.Last());
模板1.Add(last+vorletzter);
templast2.Remove(templast2.Last());
int[]array1=templast1.ToArray();
int[]array2=templast2.ToArray();
if(nEtappen>=teilstrecken.Length)
{
返回数组1.Max();
}
返回Math.Min(recursiveMin(array1,days),Math.Max(recursiveMin(array2,days-1),last));
}
但这并没有返回我想要的。
一个例子:
{64,23,56,34,23,65,28}
在3天内应返回113,但应返回90
现在我要问的是,我在实现过程中是否犯了错误,或者公式在开始时是否是错误的。
有人有主意吗?感谢转发。首先,请命名变量,以便您或其他人在6个月内理解它们的含义;)
我认为这个方法不太正确,在这里重做比较容易:
private static int recursiveMin(int[] distances, int days) {
// check for edge cases (single distance or one day)
if(distances.length == 1) {
return distances[0];
}
if(days == 1) {
int sum = 0;
for(int i=0;i<distances.length;i++) {
sum += distances[i];
}
return sum;
}
// get the last distance
int last = distances[distances.length - 1];
// create the reduced array
int[] oneLess = new int[distances.length - 1];
for(int i=0;i<oneLess.length;i++) {
oneLess[i] = distances[i];
}
// this is the max{M d−1(e1,…,en−1), en} part
int right = Math.max( recursiveMin( oneLess, days - 1 ), last );
// now use the reduced array again but add the last value on at the end
oneLess[oneLess.length - 1] += last;
// this is the Md(e1,…,e′n−1) part
int left = recursiveMin( oneLess, days );
return Math.min( left, right );
}
private static int recursiveMin(int[]距离,int天){
//检查边缘情况(单程或一天)
如果(距离.length==1){
返回距离[0];
}
如果(天数==1){
整数和=0;
对于(int i=0;i上一次调用recursiveMin
应该指定days-1
。是的,没错,但这会导致索引超出范围。作为一般建议:为变量选择一种语言。对于类似社区的帮助,英语显然是最好的选择。此外,找到描述变量的名称。名称li例如“array1”、“tempList1”等。现在让其他人很难理解代码,2个月后你自己也很难理解代码。谢谢,这很有帮助:)