본문 바로가기
알고리즘/백준 문제

2179 - 비슷한 단어

by HDobby 2023. 7. 14.

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

 

2179번: 비슷한 단어

첫째 줄에 S를, 둘째 줄에 T를 출력한다. 단, 이 두 단어는 서로 달라야 한다. 즉, 가장 비슷한 두 단어를 구할 때 같은 단어는 제외하는 것이다.

www.acmicpc.net

과정

  1. 입력을 받은 뒤 입력 받은 걸 길이를 하나씩 늘려가며 일치하는게 있는지 확인한다.
  2. 단순히 찾는건 오래걸리므로 map의 lower_bound를 이용한다.
  3. 찾아낸 string의 접두어가 일치하는지 확인한다.
  4. 문자열의 접두어 길이가 더 긴지 확인한다.
  5. 찾아낸 문자열의 접두어 길이가 같다면 해당 문자열의 idx가 저장된 idx보다 앞서는지 확인한다.
  6. map에 없는 문자열이라면 저장하고 끝!

예제

3
ab
abc
abd


ab
abc
4
aa
bb
bc
aj


aa
aj

코드

#include<iostream>
#include<map>
#include<string>

using namespace std;

int N;
map<string, int> m;

void solution(){
    string input;
    pair<int, int> cnt = {0, 987'654'321};
    pair<string, string> ans;

    cin>>N;
    for(int idx = 0; idx < N; ++idx){
        cin>>input;

        if(m.find(input) != m.end())
            continue;

        for(int i=cnt.first;i<=input.length();++i){
            string str = input.substr(0,i);

            auto it = m.lower_bound(str);

            if(it != m.end()){
                string findStr = it->first;

                if(findStr.substr(0,i).compare(str) == 0 ){
                    if((i == cnt.first && m[findStr] < cnt.second) || i > cnt.first){
                        ans = {findStr, input};
                        cnt = {i, m[findStr]};
                    }
                }
            }
        }

        m[input] = idx;
    }

    cout<<ans.first<<'\n'<<ans.second<<'\n';
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    solution();    

    return 0;
}

728x90

'알고리즘 > 백준 문제' 카테고리의 다른 글

22682 - 가장 긴 짝수 연속한 부분 수열 (large)  (0) 2023.07.15
17266 - 어두운 굴다리  (0) 2023.07.15
1446 - 지름길  (0) 2023.07.14
19942 - 다이어트  (0) 2023.07.13
19949 - 영재의 시험  (0) 2023.07.13

댓글