[C언어] 15686. 치킨배달

SW 업무 관련/백준

[C언어] 15686. 치킨배달

WillBe_ 2018. 9. 25. 17:49


DFS후, BFS로 치킨 거리를 구해줬는데...시간이 너무 오래걸려서!! 수정을 좀 해보았다.


우리는 집들의 위치를 입력 받으면서 알 수 있기 때문에 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
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <string.h>
 
typedef struct
{
    int y, x;
}point;
 
int map[55][55];
 
point Res[13];
int Res_visit[13];
 
point House[111];
int House_visit[111];
 
int N, M, Res_count, House_count, MIN;
 
int dx[] = { 0,0,-1,1 };
int dy[] = { -1,1,0,0 };
 
int abs(int a, int b){return a - b < 0 ? b - a : a - b;}
 
void DFS(int Cur, int m)
{
    if (m == M)
    {
        int Chicken_map[55][55= { 0, };
 
        for (int i = 0; i < 55; i++)
        {
            for (int j = 0; j < 55; j++)
            {
                Chicken_map[i][j] = 987654321;
            }
        }
 
        for (int i = 0; i < Res_count; i++)
        {
            if (Res_visit[i] == 1)
            {
                for (int j = 0; j < House_count; j++)
                {
                    int a = Chicken_map[House[j].y][House[j].x];//기존의 치킨 거리
                    int b = abs(House[j].y, Res[i].y) + abs(House[j].x, Res[i].x);//새로운 치킨집으로 부터의 치킨 거리
                    Chicken_map[House[j].y][House[j].x] = a < b ? a : b;//더 작은 값으로 갱신
                }
            }
        }
 
        int total = 0;
 
        for (int j = 0; j < House_count; j++)
        {
            total += Chicken_map[House[j].y][House[j].x];
        }
        if (total < MIN)
            MIN = total;
 
        return;
    }
 
    for (int i = Cur + 1; i < Res_count; i++)
    {
        Res_visit[i] = 1;
        DFS(i, m + 1);
        Res_visit[i] = 0;
    }
    return;
}
 
int main()
{
    scanf("%d %d"&N, &M);
    memset(map, -1sizeof(map));
    MIN = 987654321;
    for (int a = 1; a <= N; a++)
    {
        for (int b = 1; b <= N; b++)
        {
            scanf("%d"&map[a][b]);
            if (map[a][b] == 2)//치킨 입력
            {
                Res[Res_count].y = a;
                Res[Res_count].x = b;
                Res_count++;
            }
            else if (map[a][b] == 1)//집 입력
            {
                House[House_count].y = a;
                House[House_count].x = b;
                House_count++;
            }
        }
    }
 
    for (int i = 0; i < Res_count; i++)//M개 추리자~
    {
        Res_visit[i] = 1;
        DFS(i, 1);
        Res_visit[i] = 0;
    }
 
    printf("%d\n", MIN);
 
    return 0;
}
cs


'SW 업무 관련 > 백준' 카테고리의 다른 글

[C언어] 10164. 격자상의 경로  (0) 2018.09.25
[C언어] 14888. 연산자 끼워넣기  (0) 2018.09.25
[C언어] 14889 스타트와 링크  (0) 2018.09.25
[C언어] 14890. 경사로  (0) 2018.09.25
[C언어] 14891. 톱니바퀴  (0) 2018.09.24