【发布时间】:2020-09-04 17:51:25
【问题描述】:
昨晚我正在解决一个问题,我必须在优先级队列中插入 n 次。因此,渐近复杂度为 n log n。但是 n 可能大到 10^16,所以我必须做得更好。我找到了一个解决方案,它允许我只需要在优先级队列日志中插入 n 次,而其他所有内容都保持恒定时间。因此,复杂度为 log(n) * log(log(n))。这是我的渐近复杂度还是可以进一步简化?
这是算法。我能够通过使用 hashmap 来计算将插入优先级队列中的重复优先级并提供基于此的单一计算来降低复杂性。
我从我的代码中知道,如何将 n log n 复杂度降低到 log n log log n 可能并不直观。我必须通过示例来弄清楚它 n 减少到 log n。虽然solvedUpTo过去以与n相同的速度增加,但现在通过~n
故意将代码与它要解决的问题混淆:
fun solve(n:Long, x:Long, y:Long): Long {
val numCount = mutableMapOf<Long,Long>()
val minQue: PriorityQueue<Long> = PriorityQueue<Long>()
addToQueue(numCount,minQue,x,1)
addToQueue(numCount,minQue,y,1)
var answer = x + y
var solvedUpTo = 2L
while (solvedUpTo < n) {
val next = minQue.poll()
val nextCount = numCount.remove(next)!!
val quantityToSolveFor = min(nextCount,n - solvedUpTo)
answer = ((answer + ((next + x + y) * quantityToSolveFor))).rem(1000000007)
addToQueue(numCount,minQue,next + x,quantityToSolveFor)
addToQueue(numCount,minQue,next + y,quantityToSolveFor)
solvedUpTo += quantityToSolveFor
}
return answer
}
fun <K> addToQueue(numCount: MutableMap<K,Long>, minQue: PriorityQueue<K>, num: K, incrementBy: Long) {
if (incrementMapAndCheckIfNew(numCount, num, incrementBy)) {
minQue.add(num)
}
}
//Returns true if just added
fun <K> incrementMapAndCheckIfNew(map: MutableMap<K,Long>, key: K, incrementBy: Long): Boolean {
val prevKey = map.putIfAbsent(key,0L)
map[key] = map[key]!! + incrementBy
return prevKey == null
}
【问题讨论】:
-
请edit您的问题包括您用作优先队列的算法和数据结构。您对算法的复杂性做出了可能不正确的假设。
-
我添加了代码。它在 Kotlin 中。
标签: math big-o complexity-theory