본문 바로가기
자료구조와 알고리즘/[Inflearn_큰돌] 10주 완성 C++ 코딩테스트

3주차-5 16234번: 인구 이동

by 헛둘이 2024. 10. 21.

 

- 요약하면 국경선을 공유하는 두 나라의 인구 차이가 l 이상이고, r 이하라면, 인구 이동이 일어난다.

- 인구 이동이 일어나면, 각 칸의 인구수는 (연합의 인구수 / 연합을 이루는 칸의 개수)가 된다.

 

#include <bits/stdc++.h>
using namespace std;

int day;
int n, l, r;
int a[54][54];
int visited[54][54];
int dy[] = {-1, 0, 1, 0};
int dx[] = {0, 1, 0, -1};
int tot;
int cnt;
vector <pair<int, int>> v;

void dfs(int y, int x) {
    visited[y][x] = 1;
    tot += a[y][x];
    cnt++;
    v.push_back({y, x});
    for (int i = 0; i < 4; i++) {
        int ny = y + dy[i];
        int nx = x + dx[i];
        if (ny < 0 || ny >= n || nx < 0 || nx >= n) continue;
        if (visited[ny][nx]) continue;
        if (abs(a[ny][nx] - a[y][x]) > r || abs(a[ny][nx] - a[y][x]) < l) continue;
        dfs(ny, nx);
    }
}

int main() {
    cin >> n >> l >> r;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> a[i][j];
        }
    }

    while (true) {
        int flag = 0;
        fill(&visited[0][0], &visited[0][0] + 54*54, 0); // 초기화
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (!visited[i][j]) {
                    tot = 0;
                    cnt = 0;
                    v.clear();
                    dfs(i, j);
                    if (cnt > 1) { // 연합이 형성된 경우
                        tot /= cnt;
                        for (auto it : v) {
                            a[it.first][it.second] = tot;
                        }
                        flag = 1;
                    }
                }
            }
        }
        if (!flag) break; // 더 이상 인구 이동이 없으면 종료
        day++;
    }

    cout << day << '\n';
    return 0;
}

 

댓글