본문 바로가기
백준 알고리즘/시뮬레이션

백준 이차원 배열과 연산 C++

by paysmile 2019. 10. 17.

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
const int MAX = 101;
int num[MAX][MAX];
int r, c, k;
int indexi, indexj;

bool cmp(pair<int,int> a, pair<int,int> b) {
	if (a.second < b.second)
		return true;
	else if (a.second == b.second)
		return a.first < b.first;
	else
		return false;
}

void rowchange() {
	int maxsize = 0;
	vector<pair<int, int>> v;

	for (int i = 1; i <= indexi; i++) {
		int size = 0;
		v.clear();
		for (int j = 1; j <= indexj; j++) {
			if (num[i][j] == 0)
				continue;
			int flag = 0;
			for (int k = 0; k < v.size(); k++) {
				if (v[k].first == num[i][j]) {
					flag = 1;
					v[k] = make_pair(num[i][j], v[k].second+1);
					break;
				}
			}
			if (flag == 0)
				v.push_back(make_pair(num[i][j], 1));
		}
		size = v.size()*2;
		maxsize = max(maxsize,size);
		sort(v.begin(), v.end(),cmp);

		int index = 1;
		for (int k = 0; k < v.size(); k++) {
			num[i][index] = v[k].first;
			num[i][index + 1] = v[k].second;
			index += 2;
		}
		if (v.size() < indexj) {
			for (int k = v.size() * 2 + 1; k <= indexj; k++)
				num[i][k] = 0;
		}
	}
	indexj = maxsize;
}

void columnchange() {
	int maxsize = 0;
	vector<pair<int, int>> v;

	for (int j = 1; j <= indexj; j++) {
		int size = 0;
		v.clear();
		for (int i = 1; i <= indexi; i++) {
			if (num[i][j] == 0)
				continue;
			int flag = 0;
			for (int k = 0; k < v.size(); k++) {
				if (v[k].first == num[i][j]) {
					flag = 1;
					v[k] = make_pair(num[i][j], v[k].second+1);
					break;
				}
			}
			if (flag == 0)
				v.push_back(make_pair(num[i][j], 1));
		}
		size = v.size()*2;
		maxsize = max(maxsize, size);
		sort(v.begin(), v.end(), cmp);
		int index = 1;
		for (int k = 0; k < v.size(); k++) {
			num[index][j] = v[k].first;
			num[index+1][j] = v[k].second;
			index += 2;
		}

		if (v.size() < indexi) {
			for (int k = v.size() * 2 + 1; k <= indexi; k++)
				num[k][j] = 0;
		}
	}
	indexi = maxsize;
}

int main(void) {
	int time = 0;
	cin >> r >> c >> k;

	indexi = 3, indexj = 3;

	for (int i = 1; i <= 3; i++) {
		for (int j = 1; j <= 3; j++) {
			cin >> num[i][j];
		}
	}
	while (true) {
		if (num[r][c] == k) {
			cout << time << endl;
			break;
		}
		if (time > 100) {
			cout << -1 << endl;
			break;
		}

		if (indexi >= indexj)
			rowchange();
		else
			columnchange();
		time++;
	}
	return 0;
}

'백준 알고리즘 > 시뮬레이션' 카테고리의 다른 글

캐슬 디펜스 C++  (0) 2022.03.07
어른 상어 C++  (0) 2021.04.22
백준 낚시왕 C++  (0) 2019.10.17
백준 나무 재테크 C++  (0) 2019.10.16
백준 큐빙 C++  (0) 2019.10.15