greedydev

Untitled

Oct 17th, 2022
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.59 KB | None | 0 0
  1. protocol Stackable {
  2.     associatedtype Element
  3.     func peek() -> Element?
  4.     mutating func push(_ element: Element)
  5.     @discardableResult mutating func pop() -> Element?
  6. }
  7.  
  8. extension Stackable {
  9.     var isEmpty: Bool { peek() == nil }
  10. }
  11.  
  12. struct Stack<Element>: Stackable where Element: Equatable {
  13.     private var storage = [Element]()
  14.     func peek() -> Element? { storage.last }
  15.     mutating func push(_ element: Element) { storage.append(element)  }
  16.     mutating func pop() -> Element? { storage.popLast() }
  17. }
  18.  
  19. extension Stack: Equatable {
  20.     static func == (lhs: Stack<Element>, rhs: Stack<Element>) -> Bool { lhs.storage == rhs.storage }
  21. }
  22.  
  23. extension Stack: CustomStringConvertible {
  24.     var description: String { "\(storage)" }
  25. }
  26.    
  27. extension Stack: ExpressibleByArrayLiteral {
  28.     init(arrayLiteral elements: Self.Element...) { storage = elements }
  29. }
  30.  
  31. let instructions = readLine()!.split(separator: " ").map { Int64($0)! }
  32.  
  33. let n = instructions[0]
  34. let a = instructions[1]
  35. let b = instructions[2]
  36. let c = instructions[3]
  37. let x0 = instructions[4]
  38.  
  39. var stack = Stack<Int64>()
  40.  
  41. func getNumber(previousX: Int64) -> Int64 {
  42.     return ((a * previousX * previousX + b * previousX + c) / 100) % 1_000_000
  43. }
  44.  
  45. var prev: Int64 = x0
  46. var sum: Int64 = 0
  47.  
  48. for _ in 1...1_000_000 {
  49.     prev = getNumber(previousX: prev)
  50.     if prev % 5 < 2 {
  51.         if !stack.isEmpty {
  52.             stack.pop()
  53.         }
  54.     } else {
  55.         if let last = stack.peek() {
  56.             stack.push(min(prev, last))
  57.         } else {
  58.             stack.push(prev)
  59.         }
  60.     }
  61.    
  62.     if let last = stack.peek() {
  63.         sum += last
  64.     }
  65. }
  66.  
  67. print(sum)
Add Comment
Please, Sign In to add comment