문제: https://www.acmicpc.net/problem/1005
처음에는 bruteForce 방법으로 풀었다가 시간 초과! 그래서 memoization 방법을 이용해 시간 복잡도를 줄여 풀었습니다.
my solving
c++
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <fstream> #include <iostream> #include <algorithm> #include <vector> #include <map> #include <cstring> using namespace std; multimap<int, int> techTrees; vector<int> buildingTimes; int cache[1001]; //It used more than the allotted runtime int bruteForce(int target, int sum) { multimap<int, int>::iterator it = techTrees.find(target); if (it == techTrees.end()) return sum; int ret = 0; pair< multimap<int, int>::iterator, multimap<int, int>::iterator > p = techTrees.equal_range(target); for (it = p.first; it != p.second; it++) { ret = max(ret, bruteForce(it->second, sum + buildingTimes[it->second])); } return ret; } int dp(int target) { multimap<int, int>::iterator it = techTrees.find(target); if (it == techTrees.end()) return 0; int& ret = cache[target]; if (ret != -1) return ret; pair< multimap<int, int>::iterator, multimap<int, int>::iterator > p = techTrees.equal_range(target); for (it = p.first; it != p.second; it++) { int candidate = buildingTimes[it->second] + dp(it->second); ret = max(ret, candidate); } return ret; } int main() { int cases; cin >> cases; for (int i = 0; i < cases; i++) { techTrees.clear(); buildingTimes.clear(); int numBuilding, numTechTree, targetBuilding; cin >> numBuilding >> numTechTree; for (int i = 0; i < numBuilding; i++) { int num; cin >> num; buildingTimes.push_back(num); } for (int i = 0; i < numTechTree; i++) { int a, b; cin >> a >> b; techTrees.insert(make_pair(b - 1, a - 1)); } cin >> targetBuilding; memset(cache, -1, sizeof(cache)); int ret = buildingTimes[targetBuilding - 1] + dp(targetBuilding - 1); cout << ret << endl; } return 0; } | cs |
'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글
BAEKJOON 1007 - Vector Matching (0) | 2016.07.23 |
---|---|
BAEKJOON 1006 - 습격자 초라기 (0) | 2016.07.21 |
BAEKJOON 1004 - 어린왕자 (0) | 2016.07.12 |
BAEKJOON 1003 - 파보나치 함수 (0) | 2016.07.10 |
BAEKJOON 1002 - 터렛 (0) | 2016.07.10 |