2
这是存在气瓶堆栈的问题,您需要卸下顶部气瓶直到堆栈高度相等。我的平等堆栈算法存在哪些缺陷?
样品输入:
5 3 4
3 2 1 1 1
4 3 2
1 1 4 1
该堆叠具有5,3,和4个气缸和这些气缸的各自的高度被放在后面的行给出。
预期输出:
5
我的程序的输出:
7
我的程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
Func<string,int[]> GetIntsFromLine = (line) => Array.ConvertAll(line.Split(' '), Int32.Parse);
int numcyls = GetIntsFromLine(Console.ReadLine()).Length;
int[][] cyls = new int[numcyls][];
for(int i = 0; i < numcyls; ++i)
cyls[i] = GetIntsFromLine(Console.ReadLine());
// now the j-th cylinder stacked on the i-th stach has height cyls[i][j]
while(true)
{
var heights = from cyl in cyls
select cyl.Sum();
int h1 = heights.First();
if(heights.All(h => h == h1)) // if equal heights
{
Console.WriteLine(h1);
return;
}
// if here, "remove" the top cylinder from the stack with the largest height
int[] st = cyls[heights.ToList().IndexOf(heights.Max())];
int j = Array.IndexOf(st, 0);
st[j == -1 ? (st.Length - 1) : j] = 0;
}
}
}
https://ericlippert.com/2014/03/ 05/how-to-debug-small-programs/ – David
@David我知道如何调试。这并不能解决它们在算法中存在缺陷的问题。 – user6048670
那么特别是问题变得明显吗?当你*调试这个时,逻辑与你期望的有什么不同?到目前为止,这是一个经典的“这是我所有的代码,为我调试”的问题。 – David