๐ก๋ฌธ์ ๋ถ์ ์์ฝ
- 6๊ฐ์ ๊ตญ๊ฐ๊ฐ ์๋์ปต์์ ๊ฒฝ๊ธฐ๋ฅผ ์น๋ฅด๊ณ , ๊ฐ ๊ฒฝ๊ธฐ์ ๋ํ ์นํจ ๋๋ ๋ฌด์น๋ถ ๊ฒฐ๊ณผ๊ฐ ์ฃผ์ด์ง๋๋ฐ, ์ฃผ์ด์ง ๊ฒฐ๊ณผ๊ฐ ์ค์ ๋ก ๊ฐ๋ฅํ์ง ์ฌ๋ถ๋ฅผ ํ์ธํ๋ ๋ฌธ์ ์ด๋ค.
- ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ ์ด 15๋ฒ์ ๊ฒฝ๊ธฐ์์ ์น-ํจ, ๋ฌด์น๋ถ-๋ฌด์น๋ถ, ํจ-์น ์ค ํ๋๋ก ๊ฒฐ์ ๋๋ฉฐ, ๋ชจ๋ ๊ฒฐ๊ณผ๊ฐ ์ ์ ํ๊ฒ ๋ฐฐ๋ถ๋์ด์ผ ํ๋ค.
๐ก์๊ณ ๋ฆฌ์ฆ ์ค๊ณ
- ๊ฒฝ๊ธฐ ์กฐํฉ ์์ฑ: 6๊ฐ์ ๊ตญ๊ฐ๊ฐ ์๋ก ๊ฒฝ๊ธฐํ๋ ์กฐํฉ์ ์ด 15๊ฐ์ง์ด๋ค. ์ด ์กฐํฉ์ ๋ฏธ๋ฆฌ ๊ณ์ฐํด ๋๊ณ , ๊ฐ ๊ฒฝ๊ธฐ๋ง๋ค ์นํจ๋ ๋ฌด์น๋ถ๋ฅผ ์ ์ฉํ๋ค.
- ๋ฐฑํธ๋ํน ์ฌ๊ท ํ์: ๊ฐ ๊ฒฝ๊ธฐ์ ๋ํด 3๊ฐ์ง ๊ฐ๋ฅํ ๊ฒฐ๊ณผ(์น๋ฆฌ-ํจ๋ฐฐ, ๋ฌด์น๋ถ, ํจ๋ฐฐ-์น๋ฆฌ)๋ฅผ ์๋ํ๋ฉด์ ํด๋น ๊ฒฐ๊ณผ์ ๋ง๊ฒ ๊ตญ๊ฐ๋ณ ์น/๋ฌด/ํจ ์นด์ดํธ๋ฅผ ์กฐ์ ํ๋ค. ๋ชจ๋ ๊ฒฝ๊ธฐ๋ฅผ ์ฒ๋ฆฌํ ํ, ๊ฐ ๊ตญ๊ฐ์ ์นด์ดํธ๊ฐ 0์ด๋ฉด ์ ํจํ ๊ฒฐ๊ณผ๋ก ๊ฐ์ฃผํ๋ค.
- ๋ฐฑํธ๋ํน์ ํตํ ๋๋๋ฆฌ๊ธฐ: ๊ฒฝ๊ธฐ์ ๋ํ ๊ฒฐ๊ณผ๋ฅผ ์ ์ฉํ ํ, ์ฌ๊ท์ ์ผ๋ก ๋ค์ ๊ฒฝ๊ธฐ๋ฅผ ์ฒ๋ฆฌํ๊ณ , ํ์์ด ๋๋ ํ์๋ ์๋ ์ํ๋ก ๋๋๋ฆฐ๋ค. ์ด๋ฅผ ํตํด ๋ค๋ฅธ ๊ฐ๋ฅํ ๊ฒฝ์ฐ๋ ํ์ํ ์ ์๋ค.
๐ก์ฝ๋
const fs = require('fs');
const path = require('path');
const input = fs.readFileSync(path.join(__dirname, 'input.txt')).toString().trim().split('\\n');
const data = [];
// 6๊ฐ์ ๊ตญ๊ฐ ์ ๋ณด ์ ์ฅ
for (let i = 0; i < 4; i++) {
const temp = input[i].split(' ').map(Number);
const nation = [];
for (let j = 0; j < 6; j++) {
nation.push([temp[j * 3], temp[j * 3 + 1], temp[j * 3 + 2]]);
}
data.push(nation);
}
const cases = [];
// ๊ฒฝ๊ธฐ ์กฐํฉ ๋ฏธ๋ฆฌ ๊ณ์ฐ
for (let i = 0; i < 6; i++) {
for (let j = i + 1; j < 6; j++) {
cases.push([i, j]);
}
}
let possible = false;
function backtracking(round, nations) {
if (round === 15) {
if (nations.every(nation => nation.every(count => count === 0))) {
possible = true;
}
return;
}
const [n1, n2] = cases[round];
// ์น-ํจ
if (nations[n1][0] > 0 && nations[n2][2] > 0) {
nations[n1][0]--;
nations[n2][2]--;
backtracking(round + 1, nations);
nations[n1][0]++;
nations[n2][2]++;
}
// ๋ฌด์น๋ถ
if (nations[n1][1] > 0 && nations[n2][1] > 0) {
nations[n1][1]--;
nations[n2][1]--;
backtracking(round + 1, nations);
nations[n1][1]++;
nations[n2][1]++;
}
// ํจ-์น
if (nations[n1][2] > 0 && nations[n2][0] > 0) {
nations[n1][2]--;
nations[n2][0]--;
backtracking(round + 1, nations);
nations[n1][2]++;
nations[n2][0]++;
}
}
// 4๊ฐ์ ํ
์คํธ ์ผ์ด์ค์ ๋ํด ๊ฐ๊ฐ ์ฒ๋ฆฌ
for (let t = 0; t < 4; t++) {
possible = false;
backtracking(0, data[t]);
console.log(possible ? 1 : 0);
}
๐ก์๊ฐ๋ณต์ก๋
- 15๋ฒ์ ๊ฒฝ๊ธฐ์์ ๊ฐ๊ฐ 3๊ฐ์ง ๊ฒฐ๊ณผ๋ฅผ ๊ณ ๋ คํ๋ฏ๋ก, ์๊ฐ ๋ณต์ก๋๋ O(3^15)์ด๋ค.
- ์ด๋ ์ฝ 14,348,907๋ฒ์ ๊ฒฝ์ฐ์ ์๋ฅผ ํ์ํด์ผ ํ๋ฏ๋ก, ๋ฐฑํธ๋ํน์ผ๋ก ํ์์ ์ค์ด๋ ๊ฒ์ด ์ค์ํ๋ค.
๐กย ํ๋ฆฐ ์ด์