【发布时间】:2014-07-23 12:12:42
【问题描述】:
您有一个d[0] , d[1], d[2] , d[3] ,..,d[n] 序列。在每次移动中,您可以将任何 d[i] 增加 1 或 2 或 5 i:0 到 n 。将序列转换为 [1,2,3,..,n] if it's possible else return -1. 1<=n<=1000 排列所需的最小移动次数是多少?
我的方法是将给定数组按升序排列,而不是通过添加 1 或 2 或 5 来计数。但它在很多情况下都失败了。Some of my classmates did this in exam using this method but they read question wrong so read question carefully .
例如[1,1,3,2,1] 比答案是 4 因为我们可以通过分别添加 0,1,2,2,2 得到 [1,2,5,4,3 ] 所以答案是 4 。
[1,2,3,4,1] => [1,1,2,3,4] 我们将使用排序方法 [0,1,1,1,1] 得到 4 但答案是 2 因为我们可以在 1 中添加 [2+2] 得到 [1,2,3,4,5] 。
类似
[1,2,3,1] =>[1,1,2,3] 到 [1,2,3,4] 需要 3 次转换,但答案是 2,因为通过将 [1+2] 添加到 1我们可以得到 [1,2,3,4]。
另一种方法可以用作i don't have any proof for correctness。
Algorithm
input "n" is number of element , array "a" which contains input element
initialize cnt = 0 ;
initialize boolarray[n] ={0};
1. for i=0...n boolarray[a[i]]=1;
2. put all element in sorted order whose boolarray[a[i]]=0 for i=0...n
3. Now make boolarray[a[i]]=1; for i=0..n and count
how many additions are required .
4. return count ;
根据我的说法,这个问题总是会导致 0 或更多,因为任何数字都可以使用 1 、 2 和 5 产生,除非任何 d[i] i=0..n 大于 Inputs 的数量。
How to solve this correctly ?
欢迎任何回答和建议。
【问题讨论】:
-
解决方案总是可行的吗?对此的要求是 d[i]
-
如果没有则返回 -1 。
-
这是一道作业题吗?
-
向我们展示您的方法
-
你能展示一些你的方法失败的案例吗?并告诉我们这些情况下的正确值是多少,以及您是如何知道的。
标签: arrays algorithm int sequence permutation