Search
Duplicate
๐Ÿฅ‡

LCS 2

์ฃผ์ฐจ
12
๋ฌธ์ œ๋ฒˆํ˜ธ
9252
์–ธ์–ด
ํ‹ฐ์–ด
๊ณจ๋“œ
์œ ํ˜•
DP
nj_Blog
O
nj_์ƒํƒœ
์™„๋ฃŒ
์ดํ•ด๋„
ํ’€์ด
์‚ฌ๋žŒ
์ดํ•ด๋„ 2
13 more properties

๋ฌธ์ œ๋งํฌ

์ฝ”๋“œ ์ œ์ถœ ๊ธฐ๋ก (๋ฉ”๋ชจ๋ฆฌ ๋ฐ ์‹œ๊ฐ„)

๋ฉ”๋ชจ๋ฆฌ : 6004 KB
์‹œ๊ฐ„ : 4 ms

Code

#include <vector> #include <iostream> #include <string> #include <algorithm> std::vector<std::vector<int> > dp; std::vector<char> answer; std::string str1, str2; void preset() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); } void init(){ std::cin >> str1 >> str2; dp.resize(str1.length()+1, std::vector<int>(str2.length()+1,0)); } void solution(){ //fill dp for (int i = 1 ; i <= str1.length() ; i++){ for(int j = 1 ; j<= str2.length() ; j++){ if (str1[i-1] == str2[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = std::max(dp[i-1][j], dp[i][j-1]); } } //fill answer int k = str1.length(); for(int j = str2.length(); j>=0 ; j--){ if (dp[i][j] == 0) break; for (int i = k; i>=0 ; i--){ if (dp[i][j] == dp[i][j-1]) break; else if (dp[i][j] == dp[i-1][j]) continue; else{ answer.push_back(str1[i-1]); k = i-1; break; } } } } void output(){ std::cout << answer.size() << std::endl; while(!answer.empty()){ std::cout << answer.back(); answer.pop_back(); } std::cout << std::endl; } int main(){ preset(); init(); solution(); output(); return (0); }
C++
๋ณต์‚ฌ

๋ฉ”๋ชจ

CAPCAK ACAYKP
Plain Text
๋ณต์‚ฌ
์•„๋ž˜ ๊ทธ๋ฆผ์€ ์œ„์˜ ์ˆœ์„œ๋กœ ์ž…๋ ฅ๋ฌ๋‹ค๋Š” ๊ฐ€๋Šฅํ•˜์— ๊ทธ๋ ค์ง

<2์ฐจ์› vector ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™”>

std::vector<std::vector<int> > dp; dp.resize(str1.length()+1, std::vector<int>(str2.length()+1,0));
C++
๋ณต์‚ฌ
โ†’ 2์ฐจ์› ๋ฒกํ„ฐ๋ฅผ ์„ ์–ธํ•ด ๊ฐ€๋กœ str2.length, ์„ธ๋กœ str1.length ๋งŒํผ์„ ๋ชจ๋‘ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•จ

<C++ ์ž…์ถœ๋ ฅ ๊ฐ์ฑ„๋ฅผ ๊ฐ€์†์‹œํ‚ค๋Š” ๋ฒ•>

void preset() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); }
C++
๋ณต์‚ฌ
โ†’ cin, cout์ด scanf, printf์— ๋น„ํ•ด์„œ ์†๋„๊ฐ€ ๋งŽ์ด ๋Š๋ฆฌ๊ณ  std::endl๋ณด๋‹ค '\n'๊ฐ€ ํ›จ์”ฌ ๋น ๋ฅด๋‹ค.
โ†’ sync_with_stdio(false); ๋ฅผ ์ด์šฉํ•ด์„œ ย C++ ์ž…์ถœ๋ ฅ ๊ฐ์ฑ„๋ฅผ ๊ฐ€์†์‹œ์ผœ์„œ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋ผ๋ฉด,
scanf์™€ printf์™€ ์„ž์–ด์„œ ์‚ฌ์šฉํ•˜์ง€ ๋ง ๊ฒƒ!
์‹ฑ๊ธ€ ์“ฐ๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ๋งŒ ์‚ฌ์šฉํ•  ๊ฒƒ!
๊ทธ๋ž˜๋„ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚œ๋‹ค๋ฉด C ํ‘œ์ค€์ž…์ถœ๋ ฅ ํ•จ์ˆ˜๋“ค์„ ์‚ฌ์šฉํ•  ๊ฒƒ!

์ฐธ์กฐ

C/C++ ์ž…์ถœ๋ ฅ ๋ฐฉ๋ฒ•์— ๋”ฐ๋ฅธ ์†๋„ ์ •๋ฆฌ
๋•Œ๋Š” ๋ฐฑ์ค€ 1920๋ฒˆ ๋ฌธ์ œ๋ฅผ ํ’€ ๋•Œ ๊ฒช์€ ์ผ์ด์—ˆ์Šต๋‹ˆ๋‹ค. https://www.acmicpc.net/problem/1920 ๋ฌธ์ œ๋ฅผ ๋ณด์ž ๋งˆ์ž C++ STL์— ์žˆ๋Š” unordered_set์„ ์ด์šฉํ•˜๋ฉด ํ’€๋ฆฌ๊ฒ ๊ฑฐ๋‹ˆ, ํ•˜๊ณ  ํ’€์—ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฌ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ํ’€์ด๋ฅผ ์ฐพ์•„๋ณด๋‹ˆ ๋ฐ”์ด๋„ˆ๋ฆฌ ์„œ์น˜๋ฅผ ์ด์šฉํ•ด์„œ ํ’€๋”๊ตฐ์š”. ๊ทธ๋ž˜์„œ C++ STL Algorithm ํ—ค๋”์— ์žˆ๋Š” binary_search๋ฅผ ์ด์šฉํ•ด์„œ ํ‘ธ๋‹ˆ ๋˜‘๊ฐ™์ด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฌ์Šต๋‹ˆ๋‹ค. ์˜ˆ์ „์— C++ STL์— ์žˆ๋Š” upper_bound์™€ lower_bound๊ฐ€ O(lgN)์ด ์•„๋‹ˆ๋ผ ์„ ํ˜• ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ–๋Š”๋‹ค๋Š” ์ด์•ผ๊ธฐ๋ฅผ ๋“ค์€์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค.(ํ‹€๋ฆฐ ์ด์•ผ๊ธฐ๋ผ๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.)