寻找最少天数

时间:2016-04-22 06:57:50

标签: algorithm

我把这个问题作为采访的一部分,我仍然无法解决。 它就像这样

    A person has to complete N units of work; the nature of work is the same. 
In order to get the hang of the work, he completes only one unit of work in the first day. 
He wishes to celebrate the completion of work, so he decides to complete one unit of work in the last day. 
Given that he is only allowed to complete x, x+1 or x-1 units of work in a day, where x is the units of work 
completed on the previous day.
How many minimum days will he take to complete N units of work?

Sample Input:
6
-1
0
2
3
9
13

Here, line 1 represents the number of input test cases.

Sample Output:
0
0
2
3
5
7

Each number represents the minimum days required for each input in the sample input.

我尝试使用硬币更改方法,但无法这样做。

3 个答案:

答案 0 :(得分:3)

在2k天内,最多可以进行2T(k)工作(其中T(k)是第k个三角形数)。在2k + 1天内,在大多数工作中最多可以做T(k + 1)+ T(k)。那是因为如果有一个偶数(2k)天数,那么大部分工作是1 + 2 + 3 + ... + k + k +(k-1)+ ... 3 + 2 + 1。同样地,如果有一个奇数(2k + 1)天数,那么大部分工作是1 + 2 + 3 + ... + + + + + + + + + + + +。+

鉴于这种模式,可以将工作量减少到任何值(大于1) - 简单地减少当天完成的工作,从不选择开始或结束日。这绝不会使一天的工作量与相邻的一天相差不超过1的规则无效。

调用此函数F.即:

F(2k)   = 2T(k)
F(2k+1) = T(k)+T(k+1)

回想一下T(k)= k(k + 1)/ 2,所以方程式简化:

F(2k)   = k(k+1)
F(2k+1) = k(k+1)/2 + (k+1)(k+2)/2 = (k+1)^2

通过这些观察,您可以通过找到至少可以完成N个工作单元的最小天数来解决原始问题。即,最小的d使得F(d)> = N.

例如,您可以使用二分搜索来找到d,或者最佳方法是求解方程式。最小偶数解具有d / 2 *(d / 2 + 1)> = N,其可以求解为二次方程,并且最小奇数解具有(d + 1)^ 2/4> = N,其中有一个解决方案d = ceil(2sqrt(N)-1)。一旦你找到了最小的偶数和奇数解,你就可以选择两者中较小的一个。

答案 1 :(得分:0)

如果你想拥有最少的天数你可以说是啊x + 1,因为如果你想要最少的天数,但你必须考虑到他的最后一天x应该是1所以你必须打破在给定点并转到x-1,所以现在我们必须确定断点 断点位于日期中间,因为您从1开始并希望以1结束 例如,你必须做16个单位,所以你分配你的日子,如:
完成的工作:
1234321。  工作7天。
当你不能像上面那样做一个偶数断点时重复一些值 5 = 1211
样品:

2:11
3:111
9:12321
13:1234321

答案 2 :(得分:0)

如果你需要做N个单位而不是更多,那么你可以在矩阵a [x] [y]上使用动态编程,其中x是最后一天完成的工作量,y是总量工作,[x] [y]是所需的最少天数。您可以使用Dijkstra算法来最小化[1] [N]。以[1] [1] = 1开始。

相关问题