작성일 :

문제 링크

9636번 - NASSA’s Robot

설명

로봇이 원점에서 시작해 명령에 따라 이동합니다. 일부 명령은 누락되어 임의의 방향으로 이동했을 수 있습니다. 모든 이동 후 로봇의 좌표가 가질 수 있는 최소/최대값을 구하는 문제입니다.


접근법

확정된 이동만으로 현재 좌표를 계산하고, 누락된 명령의 개수를 셉니다.

누락 명령은 각각 한 방향으로 최대한 이동할 수 있으므로, 좌표에서 누락 수만큼 빼면 최솟값, 더하면 최댓값이 됩니다.



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
using System;
using System.Text;

class Program {
  static void Main() {
    var t = int.Parse(Console.ReadLine()!);
    var sb = new StringBuilder();
    while (t-- > 0) {
      var s = Console.ReadLine()!;
      long x = 0, y = 0, q = 0;
      foreach (var c in s) {
        if (c == 'U') y++;
        else if (c == 'D') y--;
        else if (c == 'L') x--;
        else if (c == 'R') x++;
        else q++;
      }
      long minX = x - q, maxX = x + q;
      long minY = y - q, maxY = y + q;
      sb.AppendLine($"{minX} {minY} {maxX} {maxY}");
    }
    Console.Write(sb);
  }
}

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
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int t; cin >> t;
  while (t--) {
    string s; cin >> s;
    ll x = 0, y = 0, q = 0;
    for (char c : s) {
      if (c == 'U') y++;
      else if (c == 'D') y--;
      else if (c == 'L') x--;
      else if (c == 'R') x++;
      else q++;
    }
    ll minX = x - q, maxX = x + q;
    ll minY = y - q, maxY = y + q;
    cout << minX << " " << minY << " " << maxX << " " << maxY << "\n";
  }

  return 0;
}