这是一个问题,你有一堆圆柱体,你移除顶部圆柱体,直到堆叠高度相等。
示例输入:
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;
}
}
}
答案 0 :(得分:1)
好的,让我们解决问题。所以我们有三个堆栈:
1, 1, 1, 2, 3
2, 3, 4
1, 4, 1, 1
取0,1,2,3 ......(等于删除5,4,3,2 ......)项目 从我们可以拥有的第一个堆栈
0 == 0
1 == 1
1 + 1 == 2
1 + 1 + 1 == 3
1 + 1 + 1 + 2 == 5 <- this is the solution
1 + 1 + 1 + 2 + 3 == 8
子堆。所以我们可以生产
0, 1, 2, 3, 5, 8 (from the 1st)
0, 2, 5, 9 (from the 2nd)
0, 1, 5, 6, 7 (from the 3d)
我们应该采用所有行中的最大值(可能的子包) - 5.实施:
String input =
"5 3 4\n" +
"3 2 1 1 1\n" +
"4 3 2\n" +
"1 1 4 1";
var raw = input.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Skip(1) // We don't need 1st control line
.Select(line => line
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Reverse() // <- do not forget this!
.Select(x => int.Parse(x)));
// All possible substacks per each stack
List<HashSet<int>> data = new List<HashSet<int>>();
foreach (var record in raw) {
HashSet<int> hs = new HashSet<int>() { 0 };
data.Add(hs);
int agg = 0;
foreach (var item in record)
hs.Add(agg += item);
}
// Values that are in all substacks:
HashSet<int> intersect = new HashSet<int>(data[0]);
foreach (var line in data)
intersect.IntersectWith(line);
// And, finally, the maximum one:
Console.Write(intersect.Max());