728x90
0. [c++] 백준 |
https://www.acmicpc.net/problem/2618
1. 풀이 |
2. 소스코드 |
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 86 87 88 89 | #include<iostream> #include<vector> #include<algorithm> #include<queue> using namespace std; const int INF = 1000000007; int N, W; vector<pair<int, int> > arr; int cache[1001][1001]; int ans[1001]; int dp(const int final_order_A, const int final_order_B) { int here = max(final_order_A, final_order_B) + 1; if (here == arr.size()) return 0; int & ret = cache[final_order_A][final_order_B]; if (ret != 0) return ret; ret = INF; pair<int, int> a; pair<int, int> b; if (final_order_A == 0) a = { 1,1 }; else a = arr[final_order_A]; if (final_order_B == 0) b = { N,N }; else b = arr[final_order_B]; int a_ret = abs(a.first - arr[here].first) + abs(a.second - arr[here].second) + dp(here , final_order_B); int b_ret = abs(b.first - arr[here].first) + abs(b.second - arr[here].second) + dp(final_order_A, here); ret = min(a_ret, b_ret); return ret; } void find_order(int a, int b) { int here = max(a, b) + 1; if (here == arr.size()) return; pair<int, int> c; pair<int, int> d; if (a == 0) c = { 1,1 }; else c = arr[a]; if (b == 0) d = { N,N }; else d = arr[b]; int a_ret = abs(c.first - arr[here].first) + abs(c.second - arr[here].second) + dp(here, b); int b_ret = abs(d.first - arr[here].first) + abs(d.second - arr[here].second) + dp(a, here); if (a_ret < b_ret) { ans[here] = 1; find_order(here, b); } else { ans[here] = 2; find_order(a, here); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> N >> W; int a, b; arr.push_back({ 0,0 }); for (int i = 0; i < W; i++) { cin >> a >> b; arr.push_back({ a,b }); } cout << dp(0, 0) << endl; find_order(0, 0); for (int i = 1; i <= W; i++) cout << ans[i] << endl; } | cs |
3. 참고 |
질문이나 지적 있으시면 댓글로 남겨주세요~
도움 되셨으면 하트 꾹!
'<백준> > 동적 계획법' 카테고리의 다른 글
[c++]백준 9019 - DSLR (DP) (0) | 2020.04.18 |
---|---|
[c++]백준 13913 - 숨바꼭질 4(dp) (0) | 2020.04.18 |
[c++] 백준 14003 - 가장 긴 증가하는 부분 수열 5(dp) (0) | 2020.04.17 |
[c++] 백준 14002 - 가장 긴 증가하는 부분 수열4(dp) (0) | 2020.04.17 |
[c++] 백준 12852 - 1로 만들기 2(dp) (0) | 2020.04.17 |