杭電1159 Common Subsequence【最長公用子序列】

來源:互聯網
上載者:User

標籤:blog   http   io   ar   sp   for   div   on   log   

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1159

解題思路:任意先給出兩個字串 abcfbc abfcab,用dp[i][j]來記錄當前最長的子序列,則如果有x[i]與y[j]相等的話,則相當於公用子序列的長度在dp[i-1][j-1]上增加1,

如果x[i]與y[j]不相等的話,那麼dp[i][j]就取得dp[i][j-1]和dp[i-1][j]中的最大值即可。時間複雜度為O(mn)

反思:大概思路想出來之後,因為dp數組賦初值調了很久,dp初值調出來之後,提交發現數組的長度開得不夠,改二維數組的長度又改了好久,最後弄成全域變數,水過.

#include<stdio.h>#include<string.h>int dp[1001][1001];int max(int m,int n){    if(m>n)        return m;    else        return n;}int main(){    char a[1000],b[1000];        int len1,len2;    while(scanf("%s %s",&a,&b)!=EOF)    {        int i,j;        len1=strlen(a);        len2=strlen(b);        for(i=0,j=0;j<=len2;j++)            dp[i][j]=0;        for(j=0,i=0;i<=len1;i++)            dp[i][j]=0;        for(i=0;a[i]!=‘\0‘;i++)        {            for(j=0;b[j]!=‘\0‘;j++)            {                if(a[i]==b[j])                {                    dp[i+1][j+1]=dp[i][j]+1;                }                else                {                    dp[i+1][j+1]=max(dp[i+1][j],dp[i][j+1]);                }            }        }        printf("%d\n",dp[i][j]);    }}

  

          

 

杭電1159 Common Subsequence【最長公用子序列】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.