반응형

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

 

16234번: 인구 이동

N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모

www.acmicpc.net

 

 

[ 문제풀이 ]

 

bfs를 이용하여 인접한 국가 중 인구수 범위에 들어오는 국가들의 인구를 모두 더해주고, 좌표를 vector에 저장해 이동을 하고 이동이 완료되면 ans에 1씩 더해주었습니다. 

 

그러다가 마지막에 이동이 없는 상황이 생기면 ans를 출력해주었습니다.

 

[ 소스코드 ]

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
#include<iostream>
#include<queue>
#include<vector>
#include<cstring>
 
using namespace std;
 
int N, L, R;
int arr[50][50];        //지도
int visited[50][50];    //방문 여부
int dy[4= { -1,1,0,0 };
int dx[4= { 0,0,-1,1 };
vector<pair<intint>> pos;
 
void move(int sum)
{
    for (auto next : pos) {    //이동
        int y = next.first;
        int x = next.second;
        arr[y][x] = sum / pos.size();
    }
}
 
int bfs(int y, int x) {        //연합할 국가 찾기
    queue<pair<intint>> q;
 
    q.push({ y,x });
 
    int ret = arr[y][x];    //연합할 국가의 총 인구수
    pos.push_back({ y,x });
    visited[y][x] = 1;
 
    while (!q.empty())
    {
        int y = q.front().first;
        int x = q.front().second;
        q.pop();
 
        for (int i = 0; i < 4; i++) {
            int yy = y + dy[i];
            int xx = x + dx[i];
            if (yy >= 0 && yy < N && xx >= 0 && xx < N) {
                int diff = abs(arr[y][x] - arr[yy][xx]);
 
                if (diff >= L && diff <= R && visited[yy][xx] != 1) {
                    visited[yy][xx] = 1;
                    pos.push_back({ yy,xx });
                    ret += arr[yy][xx];
                    q.push({ yy,xx });
                }
            }
        }
    }
 
    return ret;
}
 
int main()
{
    scanf("%d %d %d"&N, &L, &R);
 
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            scanf("%d"&arr[i][j]);
        }
    }
 
    int ans = 0;
 
    while (1) {
        bool flag = false;
        memset(visited, 0sizeof(visited));
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (visited[i][j] == 0) {
                    pos.clear();
                    int sum = bfs(i, j);
                    move(sum);    //이동
                    if (pos.size() > 1) flag = true;    //이동을 한번이라도 했다면
                }
            }
        }
 
        if (flag == false) {    //이동을 하지 않았다면
            printf("%d", ans);
            return 0;
        }
 
        ans++;
    }
}
cs
반응형

+ Recent posts