[백준 알고리즘] 9251번: LCS

[백준 알고리즘] 9251번: LCS (C++)

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

문제

문제 LCS(Longest Common Subsequence, 최장 공통 부분 수열)문제는 두 수열이 주어졌을 때, 모두의 부분 수열이 되는 수열 중 가장 긴 것을 찾는 문제이다.

예를 들어, ACAYKP와 CAPCAK의 LCS는 ACAK가 된다.

입력 첫째 줄과 둘째 줄에 두 문자열이 주어진다. 문자열은 알파벳 대문자로만 이루어져 있으며, 최대 1000글자로 이루어져 있다.

출력 첫째 줄에 입력으로 주어진 두 문자열의 LCS의 길이를 출력한다.

풀이

LCS 는 다른 블로그 포스팅으로 따로 정리했다.

LCS 정리

코드

#include <cstdio>

using namespace std;

int heap_size=0;

void exchange (int heap [], int a, int b){
    int temp = heap[a];
    heap[a] = heap[b];
    heap[b] = temp;
}

void min_heapify (int heap [], int n){
    int l = n*2;
    int r = n*2+1;
    int smallest;

    if (l <= heap_size && heap[l] < heap[n]) smallest = l;
    else smallest = n;

    if (r <= heap_size && heap[r] < heap[smallest]) smallest = r;

    if (smallest != n) {
        exchange(heap, smallest, n);
        min_heapify(heap, smallest);
    }
}


void push(int heap[], int num){
    heap_size++;
    int i = heap_size;

    heap[i] = num;
    while(i > 1 && heap[i/2] > heap[i]){
        exchange(heap, i, i/2);
        i = i/2;
    }
}

int pop(int heap[]){
    if (heap_size < 1) return 0;
    int r = heap[1];

    exchange(heap, 1, heap_size);

    heap_size--;
    min_heapify(heap, 1);
    return r;
}

int main(){

    int heap [100002];

    int T;
    scanf("%d", &T);

    while(T--){
        int op;
        scanf("%d", &op);
        if (op == 0) printf("%d\n", pop(heap));
        else push(heap, op);
    }

}

Written by@전여훈 (Click Me!)
고민이 담긴 코드를 만들자, 고민하기 위해 공부하자.