dev/algorithm
BOJ / 1874๋ฒ / ์คํ ์์ด [Go][Python3]
crscnt
2020. 11. 8. 21:00
๐ฉ๐ป๐ป ๋ฌธ์
1874๋ฒ: ์คํ ์์ด
1๋ถํฐ n๊น์ง์ ์์ ๋ํด ์ฐจ๋ก๋ก [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] ์ฐ์ฐ์ ์ํํ๋ฉด ์์ด [4, 3, 6, 8, 7, 5, 2, 1]์ ์ป์ ์ ์๋ค.
www.acmicpc.net
โ๐ป ํ์ด
๐จ Go
// https://www.acmicpc.net/problem/1874
// ์คํ์ ํ์ฉํ๋ ๋ฌธ์
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
writer := bufio.NewWriter(os.Stdout)
defer writer.Flush()
var n int
fmt.Fscanln(reader, &n)
var stackNum int = 1
var stackSequence []int
var result []string
for i := 0; i < n; i++ {
var input int
fmt.Fscanln(reader, &input)
if len(stackSequence) > 0 && input > stackSequence[len(stackSequence)-1] || input > stackNum {
for j := stackNum; j < input+1; j++ {
stackSequence = append(stackSequence, j)
result = append(result, "+")
stackNum++
}
stackSequence = stackSequence[:len(stackSequence)-1]
result = append(result, "-")
} else if input == stackNum {
stackSequence = append(stackSequence, input)
result = append(result, "+")
stackNum++
stackSequence = stackSequence[:len(stackSequence)-1]
result = append(result, "-")
} else if len(stackSequence) > 0 && input == stackSequence[len(stackSequence)-1] {
stackSequence = stackSequence[:len(stackSequence)-1]
result = append(result, "-")
}
}
if len(stackSequence) > 0 {
fmt.Fprintln(writer, "NO")
} else {
for _, v := range result {
fmt.Fprintln(writer, v)
}
}
}
๐จ Python3
# https://www.acmicpc.net/problem/1874
# ์คํ์ ํ์ฉํ๋ ๋ฌธ์
import sys
if __name__ == "__main__":
n = int(sys.stdin.readline())
stack_num = 1
stack_seq = []
result = []
for i in range(n):
val = int(sys.stdin.readline())
if len(stack_seq) > 0 and val > stack_seq[-1] or val > stack_num:
for j in range(stack_num, val+1):
stack_seq.append(j)
result.append("+")
stack_num += 1
stack_seq = stack_seq[:-1]
result.append("-")
elif val == stack_num:
stack_seq.append(val)
result.append("+")
stack_num += 1
stack_seq = stack_seq[:-1]
result.append("-")
elif len(stack_seq) > 0 and val == stack_seq[-1]:
stack_seq = stack_seq[:-1]
result.append("-")
if len(stack_seq) > 0:
print("NO")
else:
for v in result:
print(v)
728x90