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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<functional>
#include<cstdbool>
#include<stack>
#include<queue>
#include<vector>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define INF 987654321
#define LINF 321321321321
#define MAX 16
struct pos {
int y, x;
};
int n,w;
int distance(int y1, int x1, int y2, int x2) { return abs(y2 - y1) + abs(x2 - x1);}
int dist(pos p1,pos p2) { return abs(p1.y - p2.y) + abs(p1.x - p2.x); }
vector<pos> v;
int cache[1001][1001];
int DFS(int A, int B) {
if (A == w || B == w)
return 0;
int &ret = cache[A][B];
if (ret != -1)
return ret;
int next = max(A, B) + 1;
ret = INF;
int dist1, dist2;
if (A == 0)
dist1 = distance(1, 1, v[next].y, v[next].x);
else
dist1 = dist(v[A], v[next]);
if (B == 0)
dist2 = distance(n, n, v[next].y, v[next].x);
else
dist2 = dist(v[B], v[next]);
int ret1 = min(ret, DFS(next, B) + dist1);
int ret2 = min(ret, DFS(A, next) + dist2);
ret = min(ret1, ret2);
return ret;
}
void record(int A, int B) {
if (A == w || B == w)
return;
int next = max(A, B) + 1;
int dist1, dist2;
if (A == 0)
dist1 = distance(1, 1, v[next].y, v[next].x);
else
dist1 = dist(v[A], v[next]);
if (B == 0)
dist2 = distance(n, n, v[next].y, v[next].x);
else
dist2 = dist(v[B], v[next]);
int ret1 = cache[next][B]+dist1;
int ret2 = cache[A][next]+dist2;
if (ret1 < ret2) {
cout << "1\n";
record(next, B);
}
else {
cout << "2\n";
record(A, next);
}
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> w;
v.push_back({ 0,0 });
for (int i = 0; i < w; i++) {
int y, x;
cin >> y >> x;
v.push_back({ y,x });
}
memset(cache, -1, sizeof(cache));
cout << DFS(0, 0)<<"\n";
record(0, 0);
return 0;
}
|
cs |
출처:https://www.acmicpc.net/problem/2618
'알고리즘 > BAEKJOON' 카테고리의 다른 글
[c++]백준 2662번 기업투자 (dp,배낭) (0) | 2022.10.13 |
---|---|
[c++] 백준 7579번 앱 (dp,배낭) (1) | 2022.10.13 |
[c++] 백준 1102번 발전소 (tsp) (0) | 2022.10.12 |
[c++] 구간 합 구하기5 (1) | 2022.10.11 |
[c++] 1043번 거짓말 (유니온 파인드) (0) | 2022.09.27 |