16234번 인구 이동

동도리동·2021년 9월 17일
0

코딩테스트

목록 보기
39/76

재밌는 문제였다. for문을 2번 돌릴 때, dx[i]가 아닌 dx[k]로 정확히 확인하자. 이거때문에 시간 좀 잡아먹었당..

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <tuple>
#include <string.h>
using namespace std;
int map[50][50];
int dx[4] = { 0,0,1,-1};
int dy[4] = { 1,-1,0,0 };
int n, a, b;
void pf() {
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cout << map[i][j] << " ";
		}
		cout << '\n';
	}
}
int main() {
	
	//freopen("in1.txt", "rt", stdin);
	cin >> n >> a >> b;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cin >> map[i][j];
		}
	}
	//pf();
	int ans = 0;
	
	while (1) {
		int flag = 0;
		vector<vector<int>> ch(n, vector<int>(n,0));
//		memset(ch, 0, sizeof(ch));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				int num = map[i][j];
				//int cnt = 1;
				queue<pair<int, int>> Q;
				int x, y;
				vector<pair<int, int>> v;
				v.push_back(make_pair(i, j));
				Q.push(make_pair(i, j));
				if (ch[i][j] == 1) continue;
				ch[i][j] = 1;
				while (!Q.empty()) {
					tie(x, y) = Q.front(); Q.pop();
					
					for (int k = 0; k < 4; k++) {
						int xx = x + dx[k];
						int yy = y + dy[k];
						//cout << xx << " " << yy << '\n';
						if (xx >= n || xx < 0 || yy >= n || yy < 0) continue;
						if (ch[xx][yy] == 0) {
							
							if (abs(map[x][y] - map[xx][yy]) >= a && abs(map[x][y] - map[xx][yy]) <= b) {
								num += map[xx][yy];
								//cnt++;
								v.push_back(make_pair(xx, yy));
								ch[xx][yy] = 1;
								Q.push(make_pair(xx, yy));
								//cout << xx << " " << yy << '\n';
							}
						}
					}
				}
				if (v.size()>1) {
					num = num / v.size();
					for (int k = 0; k < v.size(); k++) {
						map[v[k].first][v[k].second] = num;
					}
					flag = 1;
				}
			}
		}
		if (flag == 0) break;
		ans++;
		//pf();
	}
	
	cout << ans << '\n';
	return 0;
}
profile
긍정코딩세상

0개의 댓글

관련 채용 정보