hdu 1159 (最長公用子序列)

來源:互聯網
上載者:User

//f(i,j)= {f(i-1,j-1)+1 (a[i]==b[j])
 //        max(f(i-1,j),f(i,j-1)) (a[i]!=b[j])
//
//由於f(i,j)只和f(i-1,j-1), f(i-1,j)和f(i,j-1)有關, 而在計算f(i,j)時, 只要選擇一個合適的順序, 就可以保證這三項都已經計算出來了, 這樣就可以計算出f(i,j). 這樣一直推到f(len(a),len(b))就得到所要求的解了.

#include<iostream>//2308270 2010-04-07 20:00:44 Accepted 1159 78MS 4216K 692 B C++ 悔惜晟
#include<algorithm>
#include<string>
using namespace std;
int num[1005][1005];
int main()
{
 char str1[1005], str2[1005];
 int i, j, len1, len2;
 while(cin>>str1>>str2)
 {
  memset(num, 0, sizeof(num));
  len1 = strlen(str1);
  len2 = strlen(str2);
  /*for(i = 0; i < len2; i++)
   for(j = 0; j < len1; j++)
   {
    if(str2[i] == str1[j])
    {
     num[0][j] = 1;
     num[i][0] = 1;
    }
   }*/
  for(i = 1; i <= len1; i++)
   for(j = 1; j <= len2; j++)
   {
    if(str1[i - 1] == str2[j - 1])
     num[i][j] = num[i-1][j-1] + 1;
    else
     num[i][j] = max(num[i-1][j] , num[i][j-1]);

   }

  printf("%d/n", num[len1][len2]);
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.