알고리즘 문제/BOJ
2839번 설탕 배달
parkit
2018. 9. 24. 22:03
728x90
반응형
나는 2가지 풀이 방법으로 풀었다.
1. 무식하게 구현(완전 탐색, 브루트 포스)
2. BFS
https://www.acmicpc.net/problem/2839
<무식하게 찾아내기(완전 탐색, 브루트 포스)>
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 | #include <iostream> #include <queue> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> using namespace std; int main(void) { int N = 0; scanf("%d", &N); int sum = 987654321; for (int x = 0; x <= N; x++) { for (int y = 0; y <= N; y++) { if (5 * x + 3 * y > N) continue; if (5 * x + 3 * y == N) { sum = min(sum, x + y); } } } if (sum == 987654321) printf("-1\n"); else printf("%d\n", sum); return 0; } | cs |
<BFS>
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | #include <iostream> #include <queue> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> using namespace std; int BFS(int start) { queue<int> q; bool visit[5001] = { false, }; memset(visit, false, sizeof(visit)); q.push(start); visit[start] = true; int ret = 0; while (!q.empty()) { int qSize = q.size(); while (qSize--) { int weight = q.front(); q.pop(); if (weight == 0) return ret; if (weight - 5 >= 0 && !visit[weight - 5]) { q.push(weight - 5); visit[weight - 5] = true; } if (weight - 3 >= 0 && !visit[weight - 3]) { q.push(weight - 3); visit[weight - 3] = true; } } ++ret; } return -1; } int main(void) { int N = 0; scanf("%d", &N); printf("%d\n", BFS(N)); return 0; } | cs |
728x90
반응형