Advertisement
Guest User

Untitled

a guest
Aug 4th, 2015
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. import scala.collection.mutable.{ Map => MMap }
  2.  
  3. object Solution {
  4. case class PrefixTrieNode(
  5. base: Char, // current node
  6. next: MMap[Char, PrefixTrieNode]) {
  7. var v: Boolean = false
  8. }
  9.  
  10. class PrefixTrieTree {
  11. val root: PrefixTrieNode = PrefixTrieNode(
  12. '\u0000',
  13. MMap[Char, PrefixTrieNode]())
  14.  
  15. val insertMonitor = new AnyRef
  16.  
  17. def put(k: String) = {
  18. var p = root
  19. for (c <- k) {
  20. insertMonitor.synchronized {
  21. if (!p.next.contains(c)) {
  22. p.next += (c -> PrefixTrieNode(c, MMap[Char, PrefixTrieNode]()))
  23. }
  24. }
  25. p = p.next.get(c).get
  26. }
  27. p.v = true
  28. }
  29.  
  30. def next(c: Char, n: PrefixTrieNode): Option[PrefixTrieNode] = n.next.get(c)
  31.  
  32. def next(c: Char): Option[PrefixTrieNode] = root.next.get(c)
  33.  
  34. def count(s: String) = {
  35. s.toCharArray.foldLeft((0, Array[PrefixTrieNode]().par)) { (l, c) =>
  36. val n = l._2.flatMap { p =>
  37. next(c, p)
  38. }
  39. next(c) match {
  40. case Some(v) =>
  41. if (v.v) {
  42. (l._1 + n.count(_.v) + 1, n :+ v)
  43. } else {
  44. (l._1 + n.count(_.v), n :+ v)
  45. }
  46. case None =>
  47. (l._1 + n.count(_.v), n)
  48. }
  49. }._1
  50. }
  51. }
  52.  
  53. def main(args: Array[String]) {
  54. val bi1 = scala.math.BigInt.long2bigInt(1)
  55. val r = new PrefixTrieTree()
  56. r.put("1".toString);
  57. (0 to 800).par.foldLeft(bi1) { (l, c) => val v = l * 2; r.put(v.toString); v }
  58. (1 to Console.in.readLine().toInt).map { i =>
  59. (Console.in.readLine(), i)
  60. }.par.map { e =>
  61. (e._2, r.count(e._1))
  62. }.toArray.sortWith(_._1 < _._1).map(_._2).foreach { v =>
  63. println(v)
  64. }
  65.  
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement