Muscardinus

인구 이동 본문

알고리즘 문제/[삼성 SW 역량 테스트 기출 문제]

인구 이동

Muscardinus 2020. 8. 31. 18:10
728x90

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

 

16234번: 인구 이동

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

www.acmicpc.net

#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

struct pos {
	int y, x;
};

int n, l, r;
int map[51][51];
int answer = 0;

int dy[] = { 1,-1,0,0 };
int dx[] = { 0,0,1,-1 };

void create_area(int sy, int sx, int visited[][51], int status[][51], int index, int& count, int& sum) {

	queue<pos> q;
	pos head;
	head.y = sy;
	head.x = sx;
	visited[sy][sx] = 1;
	q.push(head);

	while (!q.empty()) {
		pos cur = q.front(); q.pop();
		status[cur.y][cur.x] = index;
		count++;
		sum += map[cur.y][cur.x];

		for (int dir = 0; dir < 4; dir++) {
			pos next;
			next.y = cur.y + dy[dir];
			next.x = cur.x + dx[dir];

			if (next.y < 0 || next.y >= n || next.x < 0 || next.x >= n) continue;
			int delta = abs(map[cur.y][cur.x] - map[next.y][next.x]);
			if (visited[next.y][next.x] == 0 && l <= delta && delta <= r) {
				visited[next.y][next.x] = 1; q.push(next);
			}
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin >> n >> l >> r;
	for (int y = 0; y < n; y++) {
		for (int x = 0; x < n; x++) {
			cin >> map[y][x];
		}
	}
	bool is_update = true;
	while (is_update) {
		is_update = false;
		int status[51][51] = { 0, };
		int count[2501] = { 0, };
		int sum[2501] = { 0, };
		int area_index = 0;
		int visited[51][51] = { 0, };
		for (int y = 0; y < n; y++) {
			for (int x = 0; x < n; x++) {
				if (status[y][x] == 0) {
					area_index++;
					create_area(y, x, visited, status, area_index, count[area_index], sum[area_index]);
				}
			}
		}
		for (int y = 0; y < n; y++) { //수정되었으면 ++
			for (int x = 0; x < n; x++) {
				int index = status[y][x];
				int avg = sum[index] / count[index];
				if (map[y][x] != avg) {
					map[y][x] = avg;
					is_update = true;
				}
			}
		}
		if (is_update) answer++;
	}
	cout << answer << "\n";
	return 0;
}
728x90

'알고리즘 문제 > [삼성 SW 역량 테스트 기출 문제]' 카테고리의 다른 글

아기상어  (0) 2020.09.01
나무 제테크  (0) 2020.09.01
치킨 배달  (0) 2020.08.30
드래곤 커브  (0) 2020.08.29
사다리 조작  (0) 2020.08.29
Comments