본문 바로가기

Algorithm/Baekjoon

[Baekjoon] 백준 C++ 16235 나무재테크

#사람마다 푼 방법이 다릅니다. 아 이런 코드도 있구나라는 생각만 가져주시면 감사하겠습니다. 제 코드에 있어서 비효율적인 부분이 있으면 댓글로 남겨놔 주시면 참고하여 성장할 수 있도록 하겠습니다!!!

 

하지만!!! 무분별한 비난은 삼가 주세요!

 

해당 문제는 처음 생각해보면 어렵게 생각할 수 있습니다. 하지만 전혀 그렇지 않습니다.

 

저는 구조체를 선언한 후 4개의 queue를 생성해서 문제를 풀었습니다.

1. tree : 나무 전체를 관리할 queue

2. temp_tree : 해당 queue가 필요한 이유는 새로 생성된 tree를 먼저 tree queue에 먼저 넣기 위해서 임시 보관용으로

3. new_tree : 기존에 있던 나무들이 번식한 후 넣어지게 되는 tree입니다. 지금 생각해보니 굳이 해당 queue에 안 넣고 바로 tree quee에 넣어도 될뻔했네요,,,!

4. dead_tree : 봄에 죽은 나무들을 보관하는 queue입니다.

 

나머지는 기본적인 구현을 통해서 어렵지 않게 문제를 풀 수 있었습니다.

#include<iostream>
#include<queue>
#define SIZE 11

struct tr {
	int x, y, age;
};

using namespace std;

queue<tr> tree;
queue<tr> new_tree;
queue<tr> temp_tree;
queue<tr> dead_tree;

int map[SIZE][SIZE];
int energy[SIZE][SIZE];
int N,K;

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

void init() {
	for (int a = 0; a < SIZE; a++) {
		for (int b = 0; b < SIZE; b++) {
			map[a][b] = 5;
		}
	}
}
void Input() {
	int M;
	cin >> N >> M >> K;
	for (int a = 1; a <= N; a++) {
		for (int b = 1; b <= N; b++) {
			cin >> energy[a][b];
		}
	}
	for (int a = 0; a < M; a++) {
		tr temp;
		cin >> temp.x;
		cin >> temp.y;
		cin >> temp.age;
		tree.push(temp);
	}
}
void spring() {
	while (tree.size() != 0) {
		tr temp = tree.front();
		tree.pop();
		if (map[temp.x][temp.y] >= temp.age) {
			map[temp.x][temp.y] -= temp.age;
			temp.age++;
			temp_tree.push(temp);
		}
		else {
			dead_tree.push(temp);
		}
	}
}
void summer() {
	while (dead_tree.size() != 0) {
		tr temp = dead_tree.front();
		dead_tree.pop();
		map[temp.x][temp.y] += temp.age / 2;
	}
}
void fall() {
	int size = temp_tree.size();
	for (int a = 0; a < size; a++) {
		tr temp = temp_tree.front();
		temp_tree.pop();
		temp_tree.push(temp);
		if (temp.age % 5 != 0) {
			continue;
		}
		for (int b = 0; b < 8; b++) {
			int rx = temp.x + dx[b];
			int ry = temp.y + dy[b];
			if (rx >= 1 && ry >= 1 && rx <= N && ry <= N) {
				tr new_t;
				new_t.x = rx;
				new_t.y = ry;
				new_t.age = 1;
				new_tree.push(new_t);
			}
		}
	}
}
void winter() {
	for (int a = 1; a <= N; a++) {
		for (int b = 1; b <= N; b++) {
			map[a][b] += energy[a][b];
		}
	}
	int size = new_tree.size();
	for (int a = 0; a < size; a++) {
		tr temp = new_tree.front();
		new_tree.pop();
		tree.push(temp);
	}
	size = temp_tree.size();
	for (int a = 0; a < size; a++) {
		tr temp = temp_tree.front();
		temp_tree.pop();
		tree.push(temp);
	}
}
void Solution() {
	for (int a = 0; a < K; a++) {
		spring();
		summer();
		fall();
		winter();
	}
	cout << tree.size();
}
void Solve() {
	init();
	Input();
	Solution();
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	Solve();
}

'Algorithm > Baekjoon' 카테고리의 다른 글

[Baekjoon] 백준 C++ 14499 주사위 굴리기  (0) 2021.09.16
[Baekjoon] 백준 C++ 15686 치킨배달  (0) 2021.09.13
[Baekjoon] C++ 12100 EASY  (0) 2021.09.12
[Baekjoon] C++ 15685 드래곤커브  (0) 2021.08.31