https://www.acmicpc.net/problem/2294
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#define X first
#define Y second
#define pb push_back
#define fastio cin.tie(0)->sync_with_stdio(0)
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define sz(v) (int)(v).size()
#define all(v) v.begin(), v.end()
#define rall(v) (v).rbegin(), (v).rend()
#define compress(v) sort(all(v)), (v).erase(unique(all(v)), (v).end())
#define OOB(x, y) ((x) < 0 || (x) >= n || (y) < 0 || (y) >= m)
#define debug(x) cout << (#x) << ": " << (x) << '\n'
using namespace std;
using ll = long long;
using ull = unsigned long long;
using dbl = double;
using ldb = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<int>;
using vs = vector<string>;
using tii = tuple<int,int,int>;
template<typename T> using wector = vector<vector<T>>;
const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const ll LNF = 1e18 + 7;
vi dist(100001, INF);
int main(){
fastio;
int n,k; cin >> n >> k;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
queue<pii> Q;
Q.push({0, 0});
while(!Q.empty()){
auto [time, cur] = Q.front(); Q.pop();
dist[cur] = time;
for(auto i : v){
auto nx = cur + i;
if(nx < 0 || nx > 100001) continue;
if(dist[nx] != INF) continue;
Q.push({time + 1, nx});
dist[nx] = time + 1;
}
}
cout << (dist[k]==INF ? -1 : dist[k]) << "\n";
return 0;
}
dp로 풀어도 되고, BFS로도 풀어도 되는 문제입니다.
BFS를 활용해서 0부터 시작해서 주어진 값을 더해주면서 BFS 탐색해주면 됩니다.