๊ณจ๋“œ5 : ๋™์ ๊ณ„ํš๋ฒ• ๋ฌธ์ œ์ด๋‹ค.

ํ’€์ด

dp[i][j] = (i, j)๋ฒˆ์งธ ์ˆ˜์—ด์˜ ์›์†Œ๋ฅผ ํฌํ•จํ–ˆ์„ ๋•Œ, ๊ฐ€์ง€๋Š” ์ตœ์žฅ ์ˆ˜์—ด์˜ ๊ธธ์ด

dp[i][j] = max(dp[i-1][j-1]~dp[0][0])

ํ•˜์ง€๋งŒ ์‹ค์ œ ๊ตฌํ˜„์„ ์ด๋Ÿฐ์‹์œผ๋กœ ํ•˜๊ฒŒ ๋˜๋ฉด, ๋กœ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚  ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ i๋ฒˆ์งธ ์›์†Œ๋ฅผ ์—…๋ฐ์ดํŠธ ํ•œ ์ดํ›„์—, dp์˜ ๊ฐ’์ด ์‚ฌ์šฉ์ด ๋˜๋Š”์ง€ ํ™•์ธํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค.

๋ฌด์กฐ๊ฑด์ ์œผ๋กœ ์ด์ „ ์›์†Œ(i)๋ฅผ ๋ณธ ๋’ค์—๋Š” ๊ฐ’์ด ํฐ ์ƒํƒœ๋กœ ์œ ์ง€๋˜๋ฉฐ, ๋‹ค์Œ ์ƒํƒœ์˜ ์ตœ์žฅ ๊ธธ์ด๋Š” ์ด ๊ฐ’์œผ๋กœ๋ถ€ํ„ฐ ๋„์ถœ๋  ์ˆ˜ ๋ฐ–์— ์—†๋‹ค. ๋”ฐ๋ผ์„œ ์ตœ์ ํ™”๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

Code

 
#include <iostream>
#include <string>
using namespace std;
int dp[1001] = {0,};
 
int main(){
    string a, b;
    cin >> a >> b;
    
    for (int i = 0; i < a.size(); i++) {
        int temp[1001];
        for (int j = 0; j < b.size(); j++) {
            temp[j] = dp[j];
        }
        for (int j = 0; j < b.size(); j++) {
            if (a[i] == b[j]) {
                int maxvalue = 0;
                for (int k = 0; k < j; k++) {
                    if (temp[k] > maxvalue) {
                        maxvalue = temp[k];
                    }
                }
                
                dp[j] = maxvalue+1;
                
            }
        }
//        for (int k = 0; k < b.size(); k++) {
//            cout << dp[k] << " ";
//        }
//        cout << '\n';
    }
    
    int ans = 0;
    for (int i = 0; i < b.size(); i++) {
        if (ans < dp[i]) {
            ans = dp[i];
        }
    }
    
    cout << ans << '\n';
    return 0;
}
 

Reference