zoj 1733 最長公用子序 經典動態規劃

來源:互聯網
上載者:User

題目地址: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1733

初始化時,需要計算所有的f[0][i]  和  f[i][0] , 狀態轉方程是 f[i][j]= if (a[i]==b[j] )  f[i-1][j-1]+1  else max(f[i-1][j],f[i][j-1])   數組開大一點·  【100】【100】 是錯了的

代碼:

#include <iostream>#include<string>using namespace std;int f[1000][1000];int max(int a,int b){  if(a>b)  return a;  else return b;}int main(){  string a,b;  while(cin>>a>>b)  {     int lengtha=a.length();     int lengthb=b.length();     for(int i=0;i<lengtha;i++)     {         int tag=0;         for(int j=0;j<=i;j++)          if(b[0]==a[j])          {            tag=1;            break;          }        if(tag==1)        f[i][0]=1;        else f[i][0]=0;     }     for(int i=0;i<lengthb;i++)     {         int tag=0;         for(int j=0;j<=i;j++)          if(a[0]==b[j])          {            tag=1;            break;          }        if(tag==1)        f[0][i]=1;        else f[0][i]=0;     }     for(int i=1;i<lengtha;i++)      for(int j=1;j<lengthb;j++)         {              if(a[i]==b[j])  f[i][j]=f[i-1][j-1]+1;              else f[i][j]=max(f[i-1][j],f[i][j-1]);         }     cout<<f[lengtha-1][lengthb-1]<<endl;  }}

聯繫我們

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