ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

[๋ฌธ์ œ]

https://www.acmicpc.net/problem/3980

 

3980๋ฒˆ: ์„ ๋ฐœ ๋ช…๋‹จ

๊ฐ๊ฐ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์— ๋Œ€ํ•ด์„œ, ๋ชจ๋“  ํฌ์ง€์…˜์˜ ์„ ์ˆ˜๋ฅผ ์ฑ„์› ์„ ๋•Œ, ๋Šฅ๋ ฅ์น˜์˜ ํ•ฉ์˜ ์ตœ๋Œ“๊ฐ’์„ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•œ๋‹ค. ํ•ญ์ƒ ํ•˜๋‚˜ ์ด์ƒ์˜ ์˜ฌ๋ฐ”๋ฅธ ๋ผ์ธ์—…์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

www.acmicpc.net

 

[ํ’€์ด]

๋‹จ์ˆœํžˆ DFS๋ฅผ ํ†ตํ•ด ์„ ์ˆ˜ ๋ฐฐ์น˜๊ฐ€ ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์กฐํ•ฉ์„ ์™„์ „ ํƒ์ƒ‰ํ•˜๋Š” ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.

 

1. position ๋ฐฐ์—ด์— ๊ฐ ์„ ์ˆ˜๋“ค์˜ ๊ฐ€๋Šฅํ•œ ํฌ์ง€์…˜๊ณผ ๋Šฅ๋ ฅ์„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

  • position์˜ i๋ฒˆ์งธ ๋ฐฐ์—ด์— [๊ฐ€๋Šฅํ•œ ํฌ์ง€์…˜, ๋Šฅ๋ ฅ] ํ˜•ํƒœ๋กœ pushํ•ฉ๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ์˜ˆ์ œ์˜ position ์ •๋ณด๋ฅผ ๋ชจ๋‘ ์ €์žฅํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

[
  [ [ 0, 100 ] ],
  [ [ 1, 80 ], [ 2, 70 ], [ 3, 70 ], [ 4, 60 ] ],
  [ [ 1, 40 ], [ 2, 90 ], [ 3, 90 ], [ 4, 40 ] ],
  [ [ 1, 40 ], [ 2, 85 ], [ 3, 85 ], [ 4, 33 ] ],
  [ [ 1, 70 ], [ 2, 60 ], [ 3, 60 ], [ 4, 85 ] ],
  [ [ 5, 95 ], [ 6, 70 ], [ 7, 60 ], [ 8, 60 ] ],
  [ [ 1, 45 ], [ 5, 80 ], [ 6, 90 ], [ 7, 50 ], [ 8, 70 ] ],
  [ [ 5, 40 ], [ 6, 90 ], [ 7, 90 ], [ 8, 40 ], [ 9, 70 ] ],
  [ [ 6, 50 ], [ 7, 70 ], [ 8, 85 ], [ 9, 50 ] ],
  [ [ 6, 66 ], [ 7, 60 ], [ 9, 80 ], [ 10, 80 ] ],
  [ [ 6, 50 ], [ 7, 50 ], [ 9, 90 ], [ 10, 88 ] ]
]

 

2. DFS๋ฅผ ํ†ตํ•ด 11๋ช…์˜ ํฌ์ง€์…˜์„ ์„ ํƒํ•˜๊ณ  ๊ฐ ๋Šฅ๋ ฅ์˜ ํ•ฉ์„ ๋”ํ•ด์ค๋‹ˆ๋‹ค.

  • visit๋ฐฐ์—ด์„ ํ†ตํ•ด ์ด๋ฏธ ์„ ํƒ๋œ ํฌ์ง€์…˜ ๊ฐ’์„ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
  • ๋งŒ์•ฝ 11๋ฒˆ์งธ ์„ ์ˆ˜๊นŒ์ง€ ํฌ์ง€์…˜์„ ๋“ฑ๋กํ•˜๋ฉด DFS์„ returnํ•ฉ๋‹ˆ๋‹ค. (0~10๋ฒˆ ์„ ์ˆ˜๋ฅผ ๋ชจ๋‘ ๋“ฑ๋กํ•˜๊ณ  idx 11์ผ ๋•Œ)

๋”ฐ๋ผ์„œ ๋Šฅ๋ ฅ์น˜ ํ•ฉ์˜ ์ตœ๋Œ€๋ฅผ ๊ตฌํ•˜๋ฉด 970์ด ๋ฉ๋‹ˆ๋‹ค.

 

[์ฝ”๋“œ]

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';

const input = fs.readFileSync(filePath).toString().split('\n');

const [C] = input[0].split(" ").map(Number);

let max = 0;

const dfs = (position, idx, visit, total) => {
    if(idx === 11) {
        if(total > max) {
            max = total;
        }
        return;
    }

    position[idx].forEach(element => {
        const [i, score] = element;
        if(!visit[i]) {
            visit[i] = true;
            dfs(position, idx + 1, visit, total + score);
            visit[i] = false
        }
    });
}

const setPosition = (position) => {
    const visit = Array.from({length: 11}, () => false);
    dfs(position, 0, visit, 0);
}

for(let i=0;i<C;i++) {
    const position = Array.from({length: 11}, () => []);
    max = 0;
    for(let j=0;j<11;j++) {
        const temp = input[11*i+1 + j].split(" ").map(Number);
        for(let k=0;k<11;k++) {
            if(temp[k] > 0) {
                position[j].push([k, temp[k]]);
            }
        }
    }
    setPosition(position);
    console.log(max);
}