문제 : https://www.acmicpc.net/problem/17952
17952번: 과제는 끝나지 않아!
성애는 이번 학기에 전공을 정말 많이 듣는다. 이로 인해 거의 매일을 과제를 하면서 보내고 있다. 그런데도 과제가 줄어들 기미가 보이지 않는데, 바로 분단위로 과제가 추가되고 있기 때문이
www.acmicpc.net
풀이방법
- 입력받은 것 첫번째가 1일 때만 stack(점수, 시간초)에 넣는다.
- stack의 마지막 원소를 1초마다 시간초를 -1 빼준다
- 시간초가 0이되면 result에 해당 점수를 더해준다.
이 문제에서 골치아팠던게 Int($0)으로만 하면 시간초과가 난다. subString을 String으로 바꿔줘야 통과가 된다.
코드
//
// main.swift
// Assignment
//
// Created by 오킹 on 2021/08/12.
// 문제 : https://www.acmicpc.net/problem/17952
// 결과 : 1108ms 시간제한 2000ms
import Foundation
//스택이용 - 시간초과
func assignmentResult() -> Int {
var assignmentCount = Int(readLine()!)!
var result = 0
var stack = [(Int,Int)]()
while assignmentCount > 0 {
//SubString -> String으로 바꿔줘야 통과함 이유: https://icksw.tistory.com/218
var assignmentInput = readLine()!.split(separator: " ").map{Int(String($0))!}
if assignmentInput.first == 1 {
stack.append((assignmentInput[1], assignmentInput[2]))
}
if !stack.isEmpty {
var endIndex = stack.endIndex-1
stack[endIndex].1 -= 1
if stack[endIndex].1 == 0 {
result += stack.popLast()!.0
}
}
assignmentCount -= 1
}
print(result)
return result
}
assignmentResult()
알게된 점
SubString은 String으로 변환 후 사용하는게 빠르다 이유 -> https://icksw.tistory.com/218
[Swift] Int(String(SubString)), Int(SubString)의 속도 차이 원인
안녕하세요 Pingu입니다🐧 백준에서 알고리즘 문제들을 Swift 언어로 풀다 보면 가끔 Int(String(Substring))은 시간 초과가 안 나는데 Int(Substring)은 시간 초과가 나는 것을 겪었었는데요, 예를 들면 아
icksw.tistory.com
반응형
'알고리즘' 카테고리의 다른 글
[투포인터] Container With Most Water - LeetCode Swift (2) | 2021.08.18 |
---|---|
[Stack] Validate Stack Sequences - LeetCode Swift (0) | 2021.08.17 |
[투포인터] Minimize Maximum Pair Sum in Array - LeetCode Swift (0) | 2021.08.11 |
[Heap] 우선순위 큐 - LeetCode Swift (0) | 2021.08.11 |
[Stack] daily-temperatures - LeetCode Swift (0) | 2021.08.09 |