티스토리 뷰
https://www.acmicpc.net/problem/1062
1062번: 가르침
첫째 줄에 단어의 개수 N과 K가 주어진다. N은 50보다 작거나 같은 자연수이고, K는 26보다 작거나 같은 자연수 또는 0이다. 둘째 줄부터 N개의 줄에 남극 언어의 단어가 주어진다. 단어는 영어 소문
www.acmicpc.net

비트마스크로 제대로 풀면 200ms 정도로도 풀 수 있는 듯..
const input = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n').map(v=>v.trim())
const [_,K] = input[0].split(' ').map(Number);
const words = input.slice(1);
const base = ['a','n','t','i','c'];
let answer = 0; // 정답.
let leftover = K-5; // 배울 수 있는 알파벳의 수 (a,n,t,i,c는 무조건 배워야함.)
let candidate = [] // 각 단어별. 단어를 읽는 데 필요한 알파벳 antic 제외.
let alpha = []; // 배워야 하는 알파벳 정리.
if(leftover<0){ // 5개는 무조건 배워야함^^
answer = 0;
}else{
let possible = words.length // 가르칠 수 있는 단어..
words.forEach(w=>{
const clear = [...new Set(w.split('').filter(v=>!base.includes(v)))]
if(clear.length<=leftover){// 배워야 되는 알파벳의 수가 배울 수 있는 알파벳의 수보다 크면 제외
alpha = [...alpha,...clear];
candidate.push(clear)
}else{ // 이런 경우는 지민쌤이 아무리 가르쳐도 못 읽는 거니까 단어 자체를 없앰.
possible--;
}
})
alpha = [...new Set(alpha)]; // 이게 배워야 할 알파벳.
if(alpha.length<=leftover){ // 배워야 되는 알파벳이 배울 수 있는 것보다 작거나 같으면 계산할 필요 없음
answer = possible
}else{
// 이제부터 탐색시작.
for(let i = 0; i<(1<<alpha.length); i++){
let sum = 0;
if(countBits(i)==leftover){ // 배울 수 있을 만큼 배웠을 때,
const learnedAlpha = alpha.filter((_,index)=>i&(1<<index)) // 배운 알파벳.
candidate.forEach(v=>{ // 각 후보단어를 읽을 수 있는 지 확인.
if(canLearn(v,learnedAlpha)){
sum++;
}
})
}
if(sum>answer) answer = sum;
}
}
}
console.log(answer)
function countBits(n){
let cnt = 0;
while(n>0){
if(n&1){
cnt++;
}
n = n>>1;
}
return cnt;
}
function canLearn(word,alpha){
for(let i = 0; i<word.length; i++){
const now = word[i];
if(!(alpha.includes(now))){
return false
}
}
return true;
}
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js)백준 15663번: N과 M (9) (0) | 2022.01.07 |
---|---|
Node.js)백준 1987번: 알파벳 (0) | 2022.01.07 |
Node.js)백준 16197번: 두 동전 (0) | 2022.01.06 |
Node.js)백준 16198번: 에너지 모으기 (0) | 2022.01.06 |
Node.js)백준 14225번: 부분수열의 합 (0) | 2022.01.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 다이나밍프로그래밍
- 은둔청년체험
- 서버개발
- 롱베케이션
- 최소공통조상
- 로드나인
- DB 생성
- MySQL
- create db
- 서버점검
- MOD
- 동적프로그래밍
- KMP
- 면접비
- create databases;
- BFS
- 투포인터 연습
- 개발자면접
- 다이나믹프로그래밍
- node.js
- 그래프
- 투포인터
- 면접질문
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
글 보관함