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