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(11, 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(11, 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, -1sizeof(cache));
    
    cout << DFS(00)<<"\n";
    record(00);
    return 0;
}
cs

출처:https://www.acmicpc.net/problem/2618

 

2618번: 경찰차

첫째 줄에는 동서방향 도로의 개수를 나타내는 정수 N(5 ≤ N ≤ 1,000)이 주어진다. 둘째 줄에는 처리해야 하는 사건의 개수를 나타내는 정수 W(1 ≤ W ≤ 1,000)가 주어진다. 셋째 줄부터 (W+2)번째 줄

www.acmicpc.net

 

+ Recent posts