BOJ 1697. μ¨λ°κΌμ§
πββοΈ[Silver I] μ¨λ°κΌμ§ - 1697
μ±λ₯ μμ½
λ©λͺ¨λ¦¬: 2676 KB, μκ°: 0 ms
λΆλ₯
λλΉ μ°μ νμ, κ·Έλν μ΄λ‘ , κ·Έλν νμ
μ μΆ μΌμ
2024λ 1μ 3μΌ 19:38:38
λ¬Έμ μ€λͺ
μλΉμ΄λ λμκ³Ό μ¨λ°κΌμ§μ νκ³ μλ€. μλΉμ΄λ νμ¬ μ N(0 β€ N β€ 100,000)μ μκ³ , λμμ μ K(0 β€ K β€ 100,000)μ μλ€. μλΉμ΄λ κ±·κ±°λ μκ°μ΄λμ ν μ μλ€. λ§μ½, μλΉμ΄μ μμΉκ° XμΌ λ κ±·λλ€λ©΄ 1μ΄ νμ X-1 λλ X+1λ‘ μ΄λνκ² λλ€. μκ°μ΄λμ νλ κ²½μ°μλ 1μ΄ νμ 2*Xμ μμΉλ‘ μ΄λνκ² λλ€.
μλΉμ΄μ λμμ μμΉκ° μ£Όμ΄μ‘μ λ, μλΉμ΄κ° λμμ μ°Ύμ μ μλ κ°μ₯ λΉ λ₯Έ μκ°μ΄ λͺ μ΄ νμΈμ§ ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€.
μ λ ₯
첫 λ²μ§Έ μ€μ μλΉμ΄κ° μλ μμΉ Nκ³Ό λμμ΄ μλ μμΉ Kκ° μ£Όμ΄μ§λ€. Nκ³Ό Kλ μ μμ΄λ€.
μΆλ ₯
μλΉμ΄κ° λμμ μ°Ύλ κ°μ₯ λΉ λ₯Έ μκ°μ μΆλ ₯νλ€.
πνμ΄
μ²μμ DFSλ‘ νλ €κ³ νλλ° DFSλ‘ νλ©΄ μλλ€λκ±Έ μμλ€.
+1, -1, *2 νλ κ°λ€μ΄ λ 벨λ³λ‘ λ΄λ €μ€λκΉ νΈλ¦¬ κ΅¬μ‘°λ‘ μκ°ν΄μ νμλ€.
κ·Έλ¦¬κ³ λ§μ½ 5μμ μμν΄μ -1ν κ°μΌλ‘ 4κ° λκ³ λ€μ +1μ ν΄μ 5κ°λλ©΄ μλ―Έ μλ λ°λ³΅μ΄λ λ€μ λλμκ°μ§ μκ² λ§λ€μ΄μ€μΌνλ€.
νλ§λλ‘ BFSλ‘ ν΄κ²°ν΄μΌνλ λ¬Έμ μ΄λ€.
int n, k;
int discovered[100001];
void BFS(int here)
{
queue<pair<int, int>> q;
q.push({ here, 0 });
discovered[n] = true;
while (q.empty() == false)
{
int here = q.front().first;
int cnt = q.front().second;
q.pop();
if (here == k)
{
cout << cnt;
return;
}
if (here + 1 < 100001)
{
if (discovered[here + 1] == false)
{
discovered[here + 1] = true;
q.push({ here + 1, cnt + 1 });
}
}
if (here - 1 >= 0)
{
if (discovered[here - 1] == false)
{
discovered[here - 1] = true;
q.push({ here - 1, cnt + 1 });
}
}
if (here * 2 >= 0 && here * 2 < 100001)
{
if (discovered[here * 2] == false)
{
discovered[here * 2] = true;
q.push({ here * 2, cnt + 1 });
}
}
}
}
πμ 체 μ½λ
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int n, k;
int discovered[100001];
void BFS(int here)
{
queue<pair<int, int>> q;
q.push({ here, 0 });
discovered[n] = true;
while (q.empty() == false)
{
int here = q.front().first;
int cnt = q.front().second;
q.pop();
if (here == k)
{
cout << cnt;
return;
}
if (here + 1 < 100001)
{
if (discovered[here + 1] == false)
{
discovered[here + 1] = true;
q.push({ here + 1, cnt + 1 });
}
}
if (here - 1 >= 0)
{
if (discovered[here - 1] == false)
{
discovered[here - 1] = true;
q.push({ here - 1, cnt + 1 });
}
}
if (here * 2 >= 0 && here * 2 < 100001)
{
if (discovered[here * 2] == false)
{
discovered[here * 2] = true;
q.push({ here * 2, cnt + 1 });
}
}
}
}
void solve()
{
cin >> n >> k;
BFS(n);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
//freopen("input.txt", "rt", stdin);
solve();
return 0;
}