NYOJ 最长公共子序列

# include<iostream>
# include<string>
# include<stdio.h>
using namespace std;
int d[1001][1001];
int main()
{
      int n,m;
      cin>>n;
      while(n--)
      {
          string s1,s2;
        cin>>s1>>s2;
        int len1 = s1.length(),len2 = s2.length();
        int i,j;
        for(i=0;i<len1;i++)
        {
            for(j=0;j<len2;j++)
            {
                if(s1[i]==s2[j])        
                {
                    if(i==0||j==0)    d[i][j]= 1;
                    else            d[i][j] = d[i-1][j-1] + 1;
                }
                else
                {
                    if(i==0&&j==0)    
                    {
                        d[i][j]= 0;
                        continue;
                    }
                    if(i==0)    
                    {
                        d[i][j]= d[i][j-1];
                        continue;
                    }
                    if(j==0)    
                    {
                        d[i][j]= d[i-1][j];
                        continue;
                    }
                    if(d[i-1][j]>=d[i][j-1])    d[i][j] = d[i-1][j];
                    else                        d[i][j] = d[i][j-1];    
                }    
            }    
        } 
        cout<<d[len1-1][len2-1]<<endl;
    }
    return 0;
} 

 

posted @ 2018-08-15 10:18  萌新上路  阅读(105)  评论(0编辑  收藏  举报