Hello Ocean! ๐ŸŒผ

[์•Œ๊ณ ๋ฆฌ์ฆ˜ ์Šคํ„ฐ๋””] ๋ฐฑ์ค€ #9251 LCS ๋ณธ๋ฌธ

Algorithm

[์•Œ๊ณ ๋ฆฌ์ฆ˜ ์Šคํ„ฐ๋””] ๋ฐฑ์ค€ #9251 LCS

bba_dda 2020. 4. 19. 00:36
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ 

LCS(Longest Common Subsequence, ์ตœ์žฅ ๊ณตํ†ต ๋ถ€๋ถ„ ์ˆ˜์—ด)

๋‘ ์ˆ˜์—ด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ชจ๋‘์˜ ๋ถ€๋ถ„ ์ˆ˜์—ด์ด ๋˜๋Š” ์ˆ˜์—ด ์ค‘ ๊ฐ€์žฅ ๊ธด ๊ฒƒ์„ ์ฐพ๋Š” ๋ฌธ์ œ.

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

=> ์—ฐ์†ํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค๋Š” ๊ฒƒ์ด ํฌ์ธํŠธ.

ํ’€์ด

2์ฐจ์› cache๋ฅผ ์ด์šฉํ•œ DP ๋ฐฉ์‹์œผ๋กœ ํ’€๋ฉด ๋œ๋‹ค. ๋ง๋กœ ํ’€์–ด ์“ด ๊ฒƒ์€ ์ดํ•ดํ•˜๊ธฐ ํž˜๋“œ๋ฏ€๋กœ ๊ทธ๋ฆผ์„ ๊ทธ๋ ค๋ณด์•˜๋‹ค.

s1 = ACAYKP

s2 = CAPCAK ๋ฅผ ์ž…๋ ฅํ–ˆ์„ ๋•Œ cache์˜ ๋ชจ์Šต์ด๋‹ค.

cache[i][j]์—๋Š” s1์˜ i ๋ฒˆ์งธ์™€ s2์˜ j ๋ฒˆ์งธ๊ฐ€ ๊ฐ™์„ ๋•Œ ๊ฐ’์ด ์ฑ„์›Œ์ง„๋‹ค. (๊ฐ™์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” 0์ด ์ฑ„์›Œ์ง„๋‹ค)

๋‘˜์ด ๊ฐ™์„ ๋•Œ, ๊ทธ๋ƒฅ 1์„ ์ฑ„์šฐ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ์ง€๋‚œ ๊ตฌ์—ญ์—์„œ ๊ฐ€์žฅ ํฐ ๊ฐ’+1์„ ์ฑ„์šด๋‹ค.

์ฒซ ๋ฒˆ์งธ ๊ทธ๋ฆผ์—์„œ ๋นจ๊ฐ„์ƒ‰ ์นธ์„ ์ฑ„์šฐ๊ธฐ ์œ„ํ•ด ํŒŒ๋ž€์ƒ‰ ์นธ๋“ค์„ ๊ณ ๋ คํ•ด์•ผ ํ•œ๋‹ค. 

๋‘ ๋ฒˆ์งธ ๊ทธ๋ฆผ์—์„œ๋Š” ๊ฐ๊ฐ ๋ถ„ํ™์ƒ‰๊ณผ ๋ณด๋ผ์ƒ‰ ์นธ์ด ์–ด๋–ป๊ฒŒ ์ฑ„์›Œ์ง€๋Š”์ง€ ํ‘œ์‹œํ•ด๋‘์—ˆ๋‹ค.

์ด๋Ÿฌํ•œ ๊ทœ์น™์œผ๋กœ cache๋ฅผ ์ฑ„์›Œ๋‚˜๊ฐ€๋ฉด ๋œ๋‹ค. 

์ œ์ผ ๋งˆ์ง€๋ง‰ row์— ์ตœ๋Œ“๊ฐ’์ด ์žˆ์„ ๊ฒƒ์ด๋ž€ ๋ณด์žฅ์ด ์—†์œผ๋ฏ€๋กœ 

๊ฐ column๋ณ„๋กœ ์ตœ๋Œ“๊ฐ’์„ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•ด์„œ ๋งจ ๋งˆ์ง€๋ง‰์—๋Š” ์ด ๋ฐฐ์—ด์•ˆ์—์„œ ์ตœ๋Œ“๊ฐ’์„ ์ฐพ์œผ๋ฉด ๋œ๋‹ค.

 

์ฝ”๋“œ 

#include <stdio.h>
#include <string.h>

using namespace std;
int main() {
	char str1[1001];
	char str2[1001];

	scanf_s("%s", str1);
	scanf_s("%s", str2);

	int len1 = strlen(str1);
	int len2 = strlen(str2);
	int cache[1001][1001] = { 0, };

	int maxC[1001] = { 0, };
	int after[1001] = { 0, };
	int M;
	for (int i = 0;i < len1;i++) {
		for (int j = 0;j < len2;j++)
			maxC[j] = after[j];
		for (int j = 0;j < len2;j++) {
			if (str1[i] == str2[j]) {
				M = 0;
				for (int k = 0;k < j;k++) {
					if (M < maxC[k])
						M = maxC[k];
				}
				cache[i][j] = M + 1;
				if (M + 1 > maxC[j])
					after[j] = M + 1;
			}
		}
	}
	int result = 0;
	for (int i = 0;i < len2;i++) {
		if (result < after[i])
			result = after[i];
	}
	printf("%d", result);
	printf("\n");
	}*/
}

maxC (๊ฐ column๋ณ„ ์ตœ๋Œ“๊ฐ’์„ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด) ์„ ํ•œ row๊ฐ€ ๋๋‚˜๊ธฐ ์ „์— ์—…๋ฐ์ดํŠธํ•˜๋ฉด, ์ œ๋Œ€๋กœ๋œ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ค์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— after๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์„œ ์ด์šฉํ•˜์˜€๋‹ค.

 

์ œ์ถœ ๊ฒฐ๊ณผ

๋ฐ˜์‘ํ˜•