[Programmers] Lv2. ๋จ์ฒด์ฌ์ง ์ฐ๊ธฐ | C++
2023. 8. 12. 12:43ใCoding Test/Programmers
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐จ๐ปํ์ด ๊ณผ์
์ ๋ DFS๋ฅผ ์ด์ฉํ์ฌ 8๋ช ์ ์บ๋ฆญํฐ๋ค์ ์์ด๋ง๋ค ์กฐ๊ฑด์์ ๊ฒ์ฌํ์์ต๋๋ค. ํ ๊ฐ์ง ์ค์ํ๋ ๊ฒ, ์กฐ๊ฑด์์ ๋ค์ฏ๋ฒ์งธ ๊ธ์์ ํด๋นํ๋ ๊ฐ๊ฒฉ์ ๋ ์บ๋ฆญํฐ ์ฌ์ด์ ์บ๋ฆญํฐ ์ซ์๋ผ๋ ๊ฑธ ๊น๋จน์์ต๋๋ค. ์ ์ฒ๋ผ ์ธ๋ฑ์ค ํ์ ๋ฐฉ์์ผ๋ก ํ ์, ๊ฐ๊ฒฉ์๋ค๊ฐ -1์ ํด์ฃผ๋ ์ถ๊ฐ ์์ ์ด ํ์ํฉ๋๋ค.
int distance = abs(sourceIndex - targetIndex) - 1;
โ๏ธ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
const vector<char> friends{ 'A', 'C', 'F', 'J', 'M', 'N', 'R', 'T' };
vector<bool> used(friends.size(), false);
struct Constraint
{
Constraint() { }
Constraint(char source, char target, char operator_, int distance) : _source(source), _target(target), _operator(operator_), _distance(distance) { }
char _source;
char _target;
char _operator;
int _distance;
};
bool IsOk(int difference, int distance, char _operator)
{
switch (_operator)
{
case '=':
return difference == distance;
case '<':
return difference < distance;
case '>':
return difference > distance;
}
return false;
}
void DFS(const vector<Constraint>& constraints, vector<char>& sequence, int& answer)
{
if (sequence.size() == friends.size())
{
bool isOk = true;
for (const auto& constraint : constraints)
{
int sourceIndex = std::distance(sequence.begin(), std::find(sequence.begin(), sequence.end(), constraint._source));
int targetIndex = std::distance(sequence.begin(), std::find(sequence.begin(), sequence.end(), constraint._target));
int difference = abs(sourceIndex - targetIndex) - 1;
if (!IsOk(difference, constraint._distance, constraint._operator))
{
isOk = false;
break;
}
}
if (isOk)
answer++;
return;
}
for (int i = 0; i < friends.size(); i++)
{
if (used[i])
continue;
sequence.push_back(friends[i]);
used[i] = true;
DFS(constraints, sequence, answer);
used[i] = false;
sequence.pop_back();
}
}
int solution(int n, vector<string> data) {
int answer = 0;
vector<Constraint> constrains;
vector<char> sequence;
for (const auto& constraint : data)
constrains.emplace_back(Constraint(constraint[0], constraint[2], constraint[3], constraint[4] - '0'));
DFS(constrains, sequence, answer);
return answer;
}
vector<char>๋ง๊ณ ๊ทธ๋ฅ string์ผ๋ก ์ฌ์ฉํ์์ด๋ ๋ ๊ฒ ๊ฐ๋ค์. ์บ๋ฆญํฐ๋ค์ ๋ํ๋ด๋ ํํ ๋ํ ๋ฌธ์์ด๋ฏ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌ์ด ๊ฐ๋ฅํ๋, next_permutation() ํจ์๋ฅผ ์ฌ์ฉํ์ผ๋ฉด ๋ ๊น๋ํ์ ๊ฒ ๊ฐ์ต๋๋ค.
728x90
๋ฐ์ํ
'Coding Test > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] Lv3. [์นด์นด์ค ์ธํด] ๋ณด์ ์ผํ | C++ (0) | 2023.10.22 |
---|---|
[Programmers] Lv3. ์ด์ค์ฐ์ ์์ํ | C++ (0) | 2023.09.10 |
[Programmers] Lv2. ์นด์นด์คํ๋ ์ฆ ์ปฌ๋ฌ๋ง๋ถ | C++ (0) | 2023.07.13 |
[Programmers] Lv2. ์์ ๊ฒ์ | C++ (0) | 2023.07.10 |
[Programmers] Lv2. ์ด๋ชจํฐ์ฝ ํ ์ธํ์ฌ | C++ (2) | 2023.07.09 |