diff --git a/code_study/Baekjoon/ts/1043.ts b/code_study/Baekjoon/ts/1043.ts new file mode 100644 index 0000000..a7d3f72 --- /dev/null +++ b/code_study/Baekjoon/ts/1043.ts @@ -0,0 +1,66 @@ +export {}; + +const input: string[] = require("fs").readFileSync(0).toString().trim().split('\n'); +const [N, M]: number[] = input[0].split(' ').map(Number); +const knowingInfo: number[] = input[1].split(' ').map(Number); +const hasTruthKnower = knowingInfo[0] > 0; + +let partyList: number[][] = []; +for(let i = 0; i < M; i++) partyList.push(input[i+2].split(' ').map(Number)); + +let group: number[] = Array.from({length: N + 1}, (_, i) => i); + +const findGroup = (x: number): number => { + if (group[x] !== x) { + group[x] = findGroup(group[x]); + } + return group[x]; +}; + +const merge = (a: number, b: number) => { + const rootA = findGroup(a); + const rootB = findGroup(b); + + if (rootA !== rootB) { + if (rootA < rootB) { + group[rootB] = rootA; + } else { + group[rootA] = rootB; + } + } +}; + +if (hasTruthKnower && knowingInfo[0] > 1) { + const firstKnower = knowingInfo[1]; + for (let i = 2; i < knowingInfo.length; i++) { + merge(firstKnower, knowingInfo[i]); + } +} + +for (const party of partyList) { + if (party.length > 2) { + const firstPerson = party[1]; + for (let i = 2; i < party.length; i++) { + merge(firstPerson, party[i]); + } + } +}; + +const truthGroupRoot: number = hasTruthKnower ? findGroup(knowingInfo[1]) : -1; + +let result: number = 0; +for (const party of partyList) { + let canLie = true; + if (hasTruthKnower) { + for (let i = 1; i < party.length; i++) { + if (findGroup(party[i]) === truthGroupRoot) { + canLie = false; + break; + } + } + } + + if (canLie) result++; +} + +console.log(result);