[백준 3234] LUKA (C#, C++) - soo:bak
작성일 :
문제 링크
설명
이동 경로를 따라가며 루카와 같은 위치 또는 인접한 8칸에 있는 시간을 모두 출력하는 문제입니다.
접근법
시간 0의 위치인 원점에서 시작해, 경로 문자를 하나씩 적용하며 좌표를 갱신합니다.
이후 매 시각마다 루카와의 거리가 가로 세로 모두 1 이하이면 해당 시간을 기록하고, 기록이 없으면 -1을 출력합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Text;
class Program {
static void Main() {
var first = Console.ReadLine()!.Split();
var x0 = int.Parse(first[0]);
var y0 = int.Parse(first[1]);
var k = int.Parse(Console.ReadLine()!);
var path = Console.ReadLine()!;
var sb = new StringBuilder();
var hit = 0;
int x = 0, y = 0;
if (Math.Abs(x - x0) <= 1 && Math.Abs(y - y0) <= 1) {
sb.AppendLine("0");
hit++;
}
for (var i = 0; i < k; i++) {
var c = path[i];
if (c == 'I') x++;
else if (c == 'S') y++;
else if (c == 'Z') x--;
else y--;
var t = i + 1;
if (Math.Abs(x - x0) <= 1 && Math.Abs(y - y0) <= 1) {
sb.AppendLine(t.ToString());
hit++;
}
}
if (hit == 0) Console.WriteLine("-1");
else Console.Write(sb.ToString());
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int x0, y0; cin >> x0 >> y0;
int k; cin >> k;
string path; cin >> path;
int x = 0, y = 0;
vi times;
if (abs(x - x0) <= 1 && abs(y - y0) <= 1)
times.push_back(0);
for (int i = 0; i < k; i++) {
char c = path[i];
if (c == 'I') x++;
else if (c == 'S') y++;
else if (c == 'Z') x--;
else y--;
int t = i + 1;
if (abs(x - x0) <= 1 && abs(y - y0) <= 1)
times.push_back(t);
}
if (times.empty()) cout << -1 << "\n";
else {
for (int t : times)
cout << t << "\n";
}
return 0;
}