백준 알고리즘(C++)

백준 16234번 인구 이동 ( C++ )

coding232624 2024. 3. 31. 10:45

문제

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

 

16234번: 인구 이동

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

www.acmicpc.net

 

해설

완탐으로 해결하는 간단한 문제

dfs의 실행 횟수보다는 인구이동이 발생했는지를 체크하는 변수가 있었으면 더 깔끔했을듯 하다.

 

코드

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
#include <bits/stdc++.h>
using namespace std;
 
int n, l, r, uPerson, uCnt, ret, a[54][54], visited[54][54];
int dx[] = {010-1};
int dy[] = {-1010};
vector<pair<intint>> v;
 
void dfs(int y, int x)
{
  visited[y][x] = 1;
  for (int i = 0; i < 4; i++)
  {
    int nx = x + dx[i];
    int ny = y + dy[i];
    if (nx < 0 || ny < 0 || nx >= n || ny >= n || visited[ny][nx])
      continue;
    if (abs(a[ny][nx] - a[y][x]) < l || abs(a[ny][nx] - a[y][x]) > r)
      continue;
    uPerson += a[ny][nx];
    v.push_back({ny, nx});
    dfs(ny, nx);
  }
}
 
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
 
  cin >> n >> l >> r;
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < n; j++)
    {
      cin >> a[i][j];
    }
  }
 
  while (true)
  {
    uCnt = 0;
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < n; j++)
      {
        if (visited[i][j])
          continue;
 
        uPerson = a[i][j];
        v.clear();
        v.push_back({i, j});
 
        uCnt++;
        dfs(i, j);
        int person = uPerson / v.size();
        for (pair<intint> p : v)
        {
          a[p.first][p.second] = person;
        }
      }
    }
    if (uCnt == n * n)
      break;
    ret++;
    fill(&visited[0][0], &visited[0][0+ 54 * 540);
  }
  cout << ret;
}
cs