티스토리 뷰

👩🏻‍💻 문제

 

3048번: 개미

T초가 지난 후에 개미의 순서를 출력한다. 첫 번째 개미 그룹은 왼쪽에서 오른쪽으로 움직이고, 두 번째 그룹은 반대 방향으로 움직인다.

www.acmicpc.net


✍🏻 풀이

🎨 Go

// https://www.acmicpc.net/problem/3048
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n1, n2 int
	fmt.Fscanln(reader, &n1, &n2)
	first, _ := reader.ReadString('\n')
	first = strings.ReplaceAll(first, "\n", "")
	second, _ := reader.ReadString('\n')
	second = strings.ReplaceAll(second, "\n", "")
	var t int
	fmt.Fscanln(reader, &t)
	fmt.Fprintln(writer, ants(first, second, t))
}

func ants(first, second string, t int) string {
	first = reverseString(first)
	r := []rune(first)
	r2 := []rune(second)
	for i := range r2 {
		r2[i] = -r2[i]
	}
	r = append(r, r2...)
	for i := 0; i < t; i++ {
		swapped := false
		for j := 0; j < len(r)-1; j++ {
			if r[j] > 0 && r[j+1] < 0 {
				if !swapped {
					r[j], r[j+1] = r[j+1], r[j]
					swapped = true
				}
			} else {
				swapped = false
			}
		}
	}

	for i := 0; i < len(r); i++ {
		if r[i] < 0 {
			r[i] = -r[i]
		}
	}

	return string(r)
}

func reverseString(str string) (result string) {
	for _, v := range str {
		result = string(v) + result
	}
	return
}

🎨 Python3

# https://www.acmicpc.net/problem/3048
import sys

def ants(first, second, t):
    first = first[::-1]
    r = [ord(i) for i in first]
    r2 = [-ord(i) for i in second]
    r.extend(r2)
    for i in range(t):
        swapped = False
        for j in range(len(r)-1):
            if r[j] > 0 and r[j+1] < 0:
                if not swapped:
                    r[j], r[j+1] = r[j+1], r[j]
                    swapped = True
            else:
                swapped = False
    for i in range(len(r)):
        if r[i] < 0:
            r[i] = -r[i]
    ans = [chr(i) for i in r]
    return "".join(ans)

if __name__ == "__main__":
    n1, n2 = map(int, sys.stdin.readline().split())
    first = sys.stdin.readline().rstrip()
    second = sys.stdin.readline().rstrip()
    t = int(sys.stdin.readline())
    print(ants(first, second, t))
728x90
댓글