์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
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 |
- JPA
- web
- ์ฐ์ ์์ ํ
- GCP
- ์ต๋จ ๊ฒฝ๋ก
- ์๋ฎฌ๋ ์ด์
- ๋ถํ ์ ๋ณต
- java
- dfs
- BFS
- ์ฌ๊ท
- c++
- ๋ฐ์ดํฌ์คํธ๋ผ
- CVE
- thymeleaf
- ์ด๋ถ ํ์
- ๋์ ํฉ
- error
- ์คํ
- ๋ฐฑํธ๋ํน
- Spring
- DP
- ๋งต
- ๋ฌธ์์ด
- ๊ทธ๋ฆฌ๋
- ์์ ์ ๋ ฌ
- dynamic debugging
- OS
- ๊ตฌํ
- Reversing
- Today
- Total
hades
[Baekjoon] 9251๋ฒ: LCS ๋ณธ๋ฌธ
๐ฅ ๋ฌธ์
https://www.acmicpc.net/problem/9251
๐ ์ค๊ณ
์ด๊ธฐ์๋ ์ผ์ฐจ์ ๋ฐฐ์ด์ ์ ์ธํ๊ณ , strA์ strB๋ฅผ ์ด์ค ๋ฐ๋ณต๋ฌธ์ผ๋ก ์ํํ๋ฉด์, ๊ฐ์ผ๋ฉด ๊ทธ ์ธ๋ฑ์ค๊น์ง์ ์ต์ฅ ๊ฑฐ๋ฆฌ๋ฅผ ์ฆ๊ฐ์ํค๋ ๋ฐฉ์์ผ๋ก ์๋ํ์ง๋ง, ์์๊ฐ ๊ณ ๋ ค๋์ง ์๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค.
๋ฐ๋ผ์, ์ด์ฐจ์ ๋ฐฐ์ด๋ก ์ ์ธํ์ฌ, dp[i][j]๋ strA์์ i๋ฒ์งธ, strB์์ j๋ฒ์งธ๊น์ง ์ต์ฅ ๊ธธ์ด๋ฅผ ์ ์ฅํ๋ค.
dp[0][0]์ ์ด๊น๊ฐ์ผ๋ก ์ด์ฉํ๊ธฐ ์ํด, ๋ฐ๋ณต๋ฌธ์ 1๋ถํฐ ๋ฌธ์์ด์ ๊ธธ์ด๊น์ง ๋ฐ๋ณตํ๋ค. ๋ฌธ์์ด์ 0๋ถํฐ ์์ํ๋ฏ๋ก, ๋ฌธ์์ด์์๋ i-1, j-1์ ์ด์ฉํ๋ค.
strA[i-1]๊ณผ strB[j-1]์ด ๊ฐ์ผ๋ฉด, dp[i][j]๋ฅผ dp[i-1][j-1]+1๋ก ๊ฐฑ์ ํ๋ค. ๋ ๋ฌธ์์ด์์ ๊ฐ๊ฐ i์ j๊ฐ ๋๊ธฐ ์ ์ ์ต์ฅ ๊ธธ์ด์ 1์ ๋ํ๋ ๊ฒ์ด๋ค.
strA[i-1]๊ณผ strB[j-1]์ด ๋ค๋ฅด๋ฉด, dp[i][j]๋ฅผ dp[i-1][j]์ dp[i][j-1] ์ค ํฐ ๊ฐ์ผ๋ก ๊ฐฑ์ ํ๋ค. dp[i-1][j]์ dp[i][j-1]๋ dp[i][j]๊ฐ ์๋ ๊ฒ ์ค์ ์ต์ฅ ๊ธธ์ด๊ฐ ์ ์ฅ๋์ด ์๋ค.
๐ ํ์ด
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int dp[1001][1001];
string strA, strB;
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> strA >> strB;
for (int i = 1; i <= strA.length(); i++) {
for (int j = 1; j <= strB.length(); j++) {
if (strA[i-1] == strB[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[strA.length()][strB.length()] << "\n";
return 0;
}