有些內容使用中英雙語,有些只有英文或中文。歡迎使用與分享任何內容,但先來信告知並標示此部落格為出處。
Some parts use both Chinese and English, but some parts use only one language. Feel free to share, but please contact me first and list this blog as your reference.

2014年2月8日 星期六

PKU OJ - 1458 Common Subsequence

The following program is my ACcepted code for PKU OJ 1458 Common Subsequence
It's a for everybody to learn and discuss.
If there is any mistake or comment, please let me know.  :D

此乃PKU 1458的AC code!
歡迎一同討論學習,如有錯誤與任何建議請留言 : )

點這裡看題目 Click here to see this Problem!


//This program is for PKU OJ 1458 Common Subsequence
//http://poj.org/problem?id=1458


/*
This progrom is just a LCS (Longest Common Subsequence) problem.
*/

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>// for the std::max
using namespace std;

#define MAX 1025

char s1[MAX], s2[MAX];
int lcs[MAX][MAX];

void initial()
{
    memset(s1, '\0', sizeof(s1));
    memset(s2, '\0', sizeof(s2));
    memset(lcs, 0, sizeof(lcs));
 
    return;
}

int countLCS()
{
    memset(lcs, 0, sizeof(lcs));
 
    int len1, len2;
 
    len1 = strlen(s1);
    len2 = strlen(s2);
 
    for(int i = 0; i< len2; i++)// for the s2
    {
        for(int j = 0; j< len1; j++)// for the s1
        {
            if(s1[j] == s2[i])
                lcs[i + 1][j + 1] = lcs[i][j] + 1;
            else
                lcs[i + 1][j + 1] = max(lcs[i][j + 1], lcs[i + 1][j]);
        }
    }
 
    return lcs[len2][len1];
}

int main()
{
    initial();
 
    while(scanf("%s %s", &s1, &s2)!=EOF)
    {
        printf("%d\n",countLCS());
    }
    return 0;
}


Please feel free to use it after adding this blog as an reference. (http://autekroy.blogspot.tw) If there is any mistake or comment, please let me know. :D

歡迎使用與分享任何內容,但請記得標示此部落格為出處。(http://autekroy.blogspot.tw/) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )

沒有留言:

張貼留言

請留下您的任何想法或建議!
Please leave any thought or comment!