r序列问题-给定序列的最大更改数

时间:2019-08-29 21:21:57

标签: r

有人可以帮助我理解CS问题吗?

问题出在New York Time Rollercoaster problem

我有一个队列:

queue <- seq(from = 1, to = 5)
 1 2 3 4 5

一个人可以贿赂在队列中在他们前面的另一个人,但最多只能贿赂2次。因此,队列序列可能类似于:

Ride: 1, 2, 3, 4, 5  # Original queue
Ride: 1, 2, 3, 5, 4  # 5 bribes number 4
Ride: 1, 2, 5, 3, 4  # 5 bribes number 3 and thus runs out of bribes and cannot move further (it does not state in the problem if 3 can "re-bribe" 5 so I assume they cannot).
Ride: 2, 1, 5, 3, 4  # 2 bribes number 1

因此,给定输入c(1, 2, 3, 4, 5),得到最终输出swaps所需的最小数量c(2, 1, 5, 3, 4)是多少。

来自here的Python代码:

def minimumBribes(q):
    moves = 0
    for pos, val in enumerate(q):
        if (val-1) - pos > 2:
            return "Too chaotic"
        for j in xrange(max(0,val-2), pos):
            if q[j] > val:
                moves+=1
    return moves

我正在尝试在R中重新创建它并了解解决方案。

1 个答案:

答案 0 :(得分:3)

这是我的想法-

minimumBribes <- function(final_q) {
  change <- final_q - seq_along(final_q)
  if(any(change > 2)) return("Too chaotic!")
  sum(change[change > 0])
}

minimumBribes(q = c(2, 1, 5, 3, 4))
[1] 3

说明-

initial_q <- 1:5
final_q <- c(2, 1, 5, 3, 4)

# calculate change in position; +ve is gain and -ve is loss
change <- final_q - initial_q

[1]  1 -1  2 -1 -1
# it is clear that if some gained x posn combined then other(s) lost x posn combined
# i.e. sum of posn gains and losses will always be 0

# therefore, to get min total swaps, simply add either gains or losses
# which in a way implies the most direct path from initial_q to final_q
sum(change[change > 0])

[1] 3