넘치게 채우기

[Codeforces Round 1004(Div.2)] - A. Adjacent Digit Sums 본문

PS/Codeforces

[Codeforces Round 1004(Div.2)] - A. Adjacent Digit Sums

riveroverflow 2025. 2. 12. 04:21
728x90
반응형

https://codeforces.com/contest/2067/problem/A

Codeforces Round 1004(Div.2) - A. Adjacent Digit Sums

문제 유형: 수학

시간 제한: 1초

메모리 제한: 256MB

 

문제

You are given two numbers x,y. You need to determine if there exists an integer n such that S(n)=x, S(n+1)=y.

Here, S(a) denotes the sum of the digits of the number a in the decimal numeral system.

 

두 정수 x, y를 받습니다. 당신은 S(n) = x, S(n+1) = y를 만족하는 n이 있는지에 대해 판별해야 합니다.

S(a)는 a의 10진수표기에서의 모든 자릿수를 더한 값을 말합니다.

 

입력

Each test contains multiple test cases. The first line contains the number of test cases t (1t500).

The description of the test cases follows.

The first line of each test case contains two integers x,y (1x1000,1y1000).

 

여러 테스트케이스로 구성됩니다.

첫째 줄에 테스트케이스의 개수 t가 주어집니다.

각 테스트케이스의 첫 줄에는 x, y 두 정수가 주어집니다.

 

출력

For each test case, print "NO" if a suitable n does not exist. Otherwise, output "YES".

You can output each letter in any case (for example, "YES", "Yes", "yes", "yEs", "yEs" will be recognized as a positive answer).

 

불가능하면 NO, 가능하면 YES를 출력하시오. 대소문자를 가리지 않습니다.

 

풀이

보통의 경우에서는 S(n+1) = S(n) + 1이다.

99999...999의 경우, 즉 k개의 9가 연속된 꼴에서는, S(n+1) = S(n) + 1 - 9*k이다.

 

두 케이스를 고려해서, 정규표현식으로 일반화하면, [0-9]*[0-8]?9*이다.

예를 들자면 891..1325714199....9가 있다고 해보자.

하위 자릿수에 k개의 9나 나열되어있고, 그 위에는 대충 어떤 식으로 구성되어있다.

이 경우, S(n+1) = S(n) + 1 - 9*k이다.

 

즉, y = x+1-9*k인데, 식을 정리하면, 9*k = x+1-y가 된다. 

유효하려면 k가 음이 아닌 정수여야 하므로, (x+1-y)/9가 음이 아닌 정수여야 한다.

 

코드

C++

#include <bits/stdc++.h>

using namespace std;

void solve() {
  int x, y;
  cin >> x >> y;

  int ans = x + 1 - y;
  if (ans >= 0 && ans % 9 == 0) {
    cout << "Yes\n";
  } else {
    cout << "No\n";
  }
}

int main(int argc, char *argv[]) {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--)
    solve();
  return 0;
}
728x90
반응형