반응형

https://www.acmicpc.net/problem/4395

 

4395번: Steps

One steps through integer points of the straight line. The length of a step must be nonnegative and can be by one bigger than, equal to, or by one smaller than the length of the previous step. What is the minimum number of steps in order to get from x to y

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. x와 y를 입력받고, dif = y - x로 갱신합니다.

 

2. tmp = (int)sqrt(dif)로 갱신하고, ans = tmp * 2 - 1로 갱신합니다. (1 + 2 + 3 + 2 + 1 = 9, 1 + 2 + 3 + 4 + 3 + 2 + 1 = 16)

 

3. tmp * tmp < dif 라면 ans++를 해주고, tmp + 0.5 < sqrt(dif) 라면 ans++ 해줍니다.

 

4. ans를 출력합니다.

 

[ 소스코드 ]

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<iostream>
#include<cmath>
 
using namespace std;
 
int n;
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> n;
 
    while (n--) {
        int x, y;
        cin >> x >> y;
 
        int dif = y - x;
        int tmp = (int)sqrt(dif);
 
        int ans = tmp * 2 - 1;
 
        if (dif == 0) {
            cout << 0 << '\n';
        }
        else {
            if (dif - tmp * tmp != 0) {
                ans++;
                if ((double)tmp + 0.5f < sqrt(dif)) {
                    ans++;
                }
            }
 
            cout << ans << '\n';
        }
    }
}
cs
반응형

+ Recent posts