๐Ÿ“ Coding Test Study/Algorithm Problem

[Baekjoon][C++] 1759๋ฒˆ ์•”ํ˜ธ ๋งŒ๋“ค๊ธฐ ๋ฌธ์ œ์„ค๋ช… ๋ฐ ์ฝ”๋“œ

ibelieveinme 2021. 4. 17. 02:36
728x90

โ–ท ๋ฌธ์ œ์„ค๋ช…

 

1759๋ฒˆ: ์•”ํ˜ธ ๋งŒ๋“ค๊ธฐ

์ฒซ์งธ ์ค„์— ๋‘ ์ •์ˆ˜ L, C๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (3 ≤ L ≤ C ≤ 15) ๋‹ค์Œ ์ค„์—๋Š” C๊ฐœ์˜ ๋ฌธ์ž๋“ค์ด ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ๋ฌธ์ž๋“ค์€ ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž์ด๋ฉฐ, ์ค‘๋ณต๋˜๋Š” ๊ฒƒ์€ ์—†๋‹ค.

www.acmicpc.net

์ฃผ์–ด์ง„ ์•”ํ˜ธ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž์—ด L ๊ฐœ์—์„œ C๊ฐœ๋ฅผ ๊ณจ๋ผ์„œ(์ˆœ์—ด) ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ.

๋‹จ, ์•”ํ˜ธ๋Š” ๋ชจ์Œ์˜ ๊ฐœ์ˆ˜๋Š” 1๊ฐœ ์ด์ƒ์ด๊ณ  ์ž์Œ์˜ ๊ฐœ์ˆ˜๋Š” 2๊ฐœ ์ด์ƒ์ธ ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.

 

โ–ท ๋ฌธ์ œํ’€์ด

์ˆœ์—ด๋ฌธ์ œ ์ด๋ฏ€๋กœ ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ DFS ๋ฐฉ๋ฒ•์œผ๋กœ ํ’€์ดํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

[ ๋ณ€์ˆ˜ ์„ค๋ช… ]

vector<char> alpha; ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๋งŒํผ ์‰ฝ๊ฒŒ ์ž…๋ ฅ๋ฐ›๊ธฐ ์œ„ํ•ด vector ์ž๋ฃŒ๊ตฌ์กฐ ์‚ฌ์šฉ(๋™์ ํ• ๋‹น)

string answer_arr = ""; ์ •๋‹ต ์ถœ๋ ฅ์„ ์‰ฝ๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด string ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•œ๋ฒˆ์— ์ถœ๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค.

 

[ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ค๋ช… ]

๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์•ŒํŒŒ๋ฒณ์˜ ๊ธธ์ด ๋‚ด์—์„œ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋Š” ๊ธธ์ด๊นŒ์ง€ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.

์žฌ๊ท€ํ•จ์ˆ˜๋Š” ๋‘๊ฐ€์ง€ ๊ฒฝ์šฐ์˜ ์ˆ˜๋กœ ๋‚˜๋ˆ ์„œ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.

 

โ‘  ํ˜„์žฌ ์ธ๋ฑ์Šค์˜ ์•ŒํŒŒ๋ฒณ์„ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ

โ‘ก ํ˜„์žฌ ์ธ๋ฑ์Šค์˜ ์•ŒํŒŒ๋ฒณ์„ ์„ ํƒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ

 

์ฆ‰, ์ฒซ๋ฒˆ์งธ ๋ฌธ์ž๋ถ€ํ„ฐ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋Š” ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๊นŒ์ง€ ์„ ํƒํ•˜๊ณ (1๋ฒˆ ๊ฒฝ์šฐ)

์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์„œ๋Š” 2๋ฒˆ์˜ ๊ฒฝ์šฐ๋กœ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.

 

์ด ๋•Œ, ํƒ์ƒ‰ํ•  ๋•Œ๋งˆ๋‹ค ์„ ํƒํ•œ ๋ฌธ์ œ์˜ ์กฐ๊ฑด์ด ๋งž๋Š”์ง€ ํ™•์ธํ•˜๊ณ  ๋งž๋‹ค๋ฉด ๊ทธ ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

 

โ–ท ์‹œ๊ฐ„๋ณต์žก๋„

์œ„ ์„ค๋ช…์—์„œ ์ ์€ 2๊ฐ€์ง€ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์•ŒํŒŒ๋ฒณ์˜ ๊ธธ์ด๋งŒํผ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ๋ฐ˜๋ณตํ•˜๋ฏ€๋กœ

O(2^N)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ–๋Š”๋‹ค. 

 

โ–ท ์ฝ”๋“œ

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

void findPassword(int, string, vector<char>&, int);
bool countMoumJaum(string&);

int main() {
	int length, count;
	vector<char> alpha;
	string answer_arr = "";

	cin >> length >> count;

	for (int i = 0; i < count; i++) {
		char x;
		cin >> x;
		alpha.push_back(x); // a t c i s w
	}
	sort(alpha.begin(), alpha.end()); // a c i s t w
	findPassword(length, answer_arr, alpha, 0);
}

void findPassword(int length, string answer, vector<char> &alpha, int alpha_index) {
	if (answer.length() == length && countMoumJaum(answer)) {
		cout << answer << "\n";
		return;
	}
	if (alpha_index >= alpha.size()) return;

	findPassword(length, answer + alpha[alpha_index], alpha, alpha_index+1);
	findPassword(length, answer, alpha, alpha_index+1);
}

bool countMoumJaum(string &answer) {
	int moum_count = 0, jaum_count = 0;

	for (char x : answer) {
		(x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') ? moum_count += 1 : jaum_count += 1;
	}
	return moum_count >= 1 && jaum_count >= 2;
}
728x90