๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/BOJ

[C++/BOJ] 9251 : LCS (DP)

728x90

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

๋ฌธ์ œ

LCS(Longest Common Subsequence, ์ตœ์žฅ ๊ณตํ†ต ๋ถ€๋ถ„ ์ˆ˜์—ด)๋ฌธ์ œ๋Š” ๋‘ ์ˆ˜์—ด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ชจ๋‘์˜ ๋ถ€๋ถ„ ์ˆ˜์—ด์ด ๋˜๋Š” ์ˆ˜์—ด ์ค‘ ๊ฐ€์žฅ ๊ธด ๊ฒƒ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด, ACAYKP์™€ CAPCAK์˜ LCS๋Š” ACAK๊ฐ€ ๋œ๋‹ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„๊ณผ ๋‘˜์งธ ์ค„์— ๋‘ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ๋ฌธ์ž์—ด์€ ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ์ตœ๋Œ€ 1000๊ธ€์ž๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ๋‘ ๋ฌธ์ž์—ด์˜ LCS์˜ ๊ธธ์ด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.


 

๋ฐฑ์ค€ ๊ณจ๋“œ5ํ‹ฐ์–ด.

 

์ฒ˜์Œ์— ์‹œ๊ฐ„์ œํ•œ์ด 0.1์ดˆ๊ธธ๋ž˜ ์™„ํƒ์œผ๋กœ๋Š” ๋ชปํ’€๊ฒ ๊ตฌ๋‚˜ ํ–ˆ๋Š”๋ฐ ์—ญ์‹œ ํ‹€๋ฆผ

๊ทธ๋ž˜์„œ ์–Œ์ „ํžˆ DP๋กœ ํ•ด๊ฒฐํ–ˆ์Šต๋‹ˆ๋‹ค..

 

์ ํ™”์‹์„ ๋– ์˜ฌ๋ฆฌ๊ธฐ ํž˜๋“ค์—ˆ๋Š”๋ฐ, ํ•œ ๋ธ”๋กœ๊ฑฐ์˜ ์ž˜ ์ •๋ฆฌ๋œ ๊ธ€์„ ์ฝ๊ณ  ์ด์ฐจ์›๋ฐฐ์—ด์„ ์ด์šฉํ•ด์„œ ํ•ด๊ฒฐํ•จ

 

์˜ˆ๋ฅผ ๋“ค์–ด, ๋ฌธ์ž์—ด์ด ABA ์™€ CADB ์ผ ๋•Œ

์•„๋ž˜์™€ ๊ฐ™์ด ํ‘œ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

 

  A B A
C don't match -> 0 0 0
A match! -> 1 1 1
D don't match -> 1 1 1
B don't match -> 1 match! -> 2 2

 

1์—ด์„ ์‚ดํŽด๋ณด๋ฉด,

๋ฌธ์ž์—ด A์™€ C ์˜ lcs length = 0

๋ฌธ์ž์—ด A์™€ CA ์˜ lcs length = 1

๋ฌธ์ž์—ด A์™€ CAD ์˜ lcs length = 1

๋ฌธ์ž์—ด A์™€ CADB ์˜ lcs length = 1

 

2์—ด์„ ์‚ดํŽด๋ณด๋ฉด,

๋ฌธ์ž์—ด AB์™€ C ์˜ lcs length = 0

๋ฌธ์ž์—ด AB์™€ CA ์˜ lcs length = 1

๋ฌธ์ž์—ด AB์™€ CAD ์˜ lcs length = 1

๋ฌธ์ž์—ด AB์™€ CADB ์˜ lcs length = 2

 

์ด์™€ ๊ฐ™์ด ๋‚˜์—ดํ•ด๋ณด๋ฉด ๊ทœ์น™์„ ์ฐพ์•„ ์•„๋ž˜์™€ ๊ฐ™์€ ์ ํ™”์‹์„ ๋– ์˜ฌ๋ฆด ์ˆ˜ ์žˆ๋‹ค.

 

if(a[i-1]==b[j-1]) {
    dp[i][j] = dp[i-1][j-1] + 1;
}
else {
    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}

 

 

 

 

๋‚˜์˜ ํ’€์ด

#include <iostream>
#include <string>
using namespace std;

int main(){
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    string a;
    string b;
    cin >> a >> b;
    int dp[1001][1001] = {{0}};

    for (int i = 1; i <= a.length(); ++i){
        for (int j = 1; j <= b.length(); ++j){
            if(a[i-1]==b[j-1]) {
                dp[i][j] = dp[i-1][j-1] + 1;
            }
            else {
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        }
    }
    cout << dp[a.length()][b.length()];
}

 

728x90