작성일 :

문제 링크

25286번 - 11월 11일

설명

y년 m월 m일에서 m일 전의 날짜를 구하는 문제입니다.


접근법

m월 m일에서 m일 전은 항상 이전 달의 마지막 날입니다.

1월이면 전년도 12월로, 아니면 이전 달로 이동합니다.

해당 달의 마지막 날을 출력하며, 2월은 윤년 여부에 따라 28일 또는 29일입니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;

class Program {
  static void Main() {
    var lastDate = new[] {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    var t = int.Parse(Console.ReadLine()!);
    while (t-- > 0) {
      var parts = Array.ConvertAll(Console.ReadLine()!.Split(), int.Parse);
      var y = parts[0];
      var m = parts[1];
      if (m == 1) { y--; m = 12; }
      else m--;

      var d = lastDate[m];
      if (m == 2) {
        if (y % 100 == 0) d = (y % 400 == 0) ? 29 : 28;
        else d = (y % 4 == 0) ? 29 : 28;
      }
      Console.WriteLine($"{y} {m} {d}");
    }
  }
}

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 lastDate[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  int t; cin >> t;
  while (t--) {
    int y, m; cin >> y >> m;
    if (m == 1) { y--; m = 12; }
    else m--;

    int d = lastDate[m];
    if (m == 2) {
      if (y % 100 == 0) d = (y % 400 == 0) ? 29 : 28;
      else d = (y % 4 == 0) ? 29 : 28;
    }
    cout << y << " " << m << " " << d << "\n";
  }

  return 0;
}