작성일 :

문제 링크

20053번 - 최소, 최대 2

설명

여러 개의 테스트 케이스가 주어지고, 각 테스트 케이스마다 정수들이 주어질 때 그 중 최솟값과 최댓값을 찾는 문제입니다.

각 테스트 케이스에서 정수의 개수는 최대 1,000,000개까지 가능하므로 빠른 입력 처리가 필요합니다.


접근법

각 테스트 케이스마다 현재까지 본 수들 중 최솟값과 최댓값을 유지하면서 정수들을 순회합니다.

최솟값은 매우 큰 값으로, 최댓값은 매우 작은 값으로 초기화한 후, 각 정수를 읽을 때마다 현재 최솟값과 최댓값을 갱신합니다.


모든 정수를 확인한 후 해당 테스트 케이스의 최솟값과 최댓값을 출력합니다.


입력 크기가 최대 1,000,000개까지 가능하므로 빠른 입출력이 필요합니다.

C#에서는 버퍼를 이용한 빠른 입력 처리를 사용하고, C++에서는 입출력 동기화를 해제하여 속도를 확보합니다.



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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.IO;

namespace Solution {
  class FastScanner {
    private readonly Stream _stream = Console.OpenStandardInput();
    private readonly byte[] _buf = new byte[1 << 16];
    private int _len, _ptr;

    private byte Read() {
      if (_ptr >= _len) {
        _len = _stream.Read(_buf, 0, _buf.Length);
        _ptr = 0;
        if (_len <= 0) return 0;
      }
      return _buf[_ptr++];
    }

    public int NextInt() {
      int c;
      do { c = Read(); } while (c <= ' ');
      bool neg = false;
      if (c == '-') { neg = true; c = Read(); }
      int val = 0;
      while (c > ' ') {
        val = val * 10 + (c - '0');
        c = Read();
      }
      return neg ? -val : val;
    }
  }

  class Program {
    static void Main(string[] args) {
      var fs = new FastScanner();
      var t = fs.NextInt();

      for (var i = 0; i < t; i++) {
        var n = fs.NextInt();
        var min = int.MaxValue;
        var max = int.MinValue;

        for (var j = 0; j < n; j++) {
          var x = fs.NextInt();
          if (x < min) min = x;
          if (x > max) max = x;
        }

        Console.WriteLine($"{min} {max}");
      }
    }
  }
}

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

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

  int t; cin >> t;

  while (t--) {
    int n; cin >> n;
    int mn = 1'000'001, mx = -1'000'001;

    for (int i = 0; i < n; i++) {
      int x; cin >> x;
      if (x < mn) mn = x;
      if (x > mx) mx = x;
    }

    cout << mn << " " << mx << "\n";
  }

  return 0;
}