

Hãy luôn nhớ cảm ơn và vote 5*
nếu câu trả lời hữu ích nhé!
Ý tưởng: Dùng BFS để tìm số túi nhỏ nhất
DPT: O(n)
Code C++:
#include<bits/stdc++.h>
using namespace std;
int n;
bool check[3000001];
int bfs()
{
queue<pair<int,int>> q;
q.push({0,0});
while(!q.empty())
{
pair<int,int> temp = q.front();
q.pop();
if(temp.first == n) return temp.second;
if(temp.first + 3 <= n && !check[temp.first + 3])
{
check[temp.first + 3] = 1;
q.push({temp.first + 3, temp.second + 1});
}
if(temp.first + 5 <= n && !check[temp.first + 5])
{
check[temp.first + 5] = 1;
q.push({temp.first + 5, temp.second + 1});
}
}
return -1;
}
int main()
{
freopen("DONGGOI.INP","r",stdin);
freopen("DONGGOI.OUT","w",stdout);
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n;
cout << bfs();
}
Hãy giúp mọi người biết câu trả lời này thế nào?
Bảng tin
