본문 바로가기

Algorithm

(C++) - 백준(BOJ) 16431번 : 베시와 데이지

반응형

https://www.acmicpc.net/problem/16431

 

16431번: 베시와 데이지

베시는 (3, 5) > (2, 4) > (2, 3) 경로로 이동하여 존에게 오는데 2초가 걸립니다. 반면 데이지는 (1, 1) > (1, 2) > (1, 3) > (2, 3) 경로로 이동하여 존에게 오는데 3초가 걸리므로 베시가 더 빨리 도착합니다.

www.acmicpc.net

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
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
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
//베시와 데이지 중 존에게 거리가 더 적은 소가 이김
int map[1001][1001];
int ck[1001][1001];
int bans[1001][1001];
int dans[1001][1001];
 
int bx[8= { 0,0,1,-1,-1,-1,1,1 };
int by[8= { 1,-1,0,0,1,-1,1,-1 };
int dx[4= { 0,0,1,-1 };
int dy[4= { 1,-1,0,0 };
int br, bc, dr, dc, jr, jc;
int b = 200000000, d = 200000000;
void B_BFS(int x,int y)
{
    memset(ck, 0sizeof(ck));
    queue <pair<int,int>> q;
    q.push({ x,y });
    ck[x][y] = 1;
    while (!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            int nx = x + bx[i];
            int ny = y + by[i];
            if (1 <= nx && nx <= 1000 && 1 <= ny && ny <= 1000)
            {
                if (map[nx][ny] == 0 && ck[nx][ny] == 0 || map[nx][ny]==2)
                {
                    ck[nx][ny] = 1;
                    bans[nx][ny] = bans[x][y] + 1;
                    q.push({ nx,ny });
                    if (map[nx][ny] == 2)
                    {
                        b = min(bans[nx][ny], b);
                    }
                }
            }
        }
    }
}
 
void D_BFS(int x, int y)
{
    memset(ck, 0sizeof(ck));
    queue <pair<intint>> q;
    q.push({ x,y });
    ck[x][y] = 1;
    while (!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if (1 <= nx && nx <= 1000 && 1 <= ny && ny <= 1000)
            {
                if (map[nx][ny] == 0 && ck[nx][ny] == 0 || map[nx][ny] == 2)
                {
                    ck[nx][ny] = 1;
                    dans[nx][ny] = dans[x][y] + 1;
                    q.push({ nx,ny });
                    if (map[nx][ny] == 2)
                    {
                        d = min(dans[nx][ny], d);
                    }
                }
            }
        }
    }
}
int main() {
    cin >> br >> bc >> dr >> dc >> jr >> jc;
    map[jr][jc] = 2;
    B_BFS(br, bc);
    D_BFS(dr, dc);
    if (b > d)
    {
        cout << "daisy" << '\n';
    }
    else if (b < d)
    {
        cout << "bessie" << '\n';
    }
    else
        cout << "tie" << '\n';
 
}
cs