最長公共子串

最長公共子串問題

      Time Limit:1000MS Memory Limit:65536KB
   

所謂最長公共子串,比如串A "acedfe", 串B "aede", 則它們的最長公共子串爲串 "aede", 即不論串中字符是否相鄰,只要它是給定各個串都包含的,且長度最長的串。給定兩個不包含空格的字符串和一整數n , 如果最長公共串長度大於或等於n,輸出Not Smaller, 否則輸出Smaller.
第一行僅一個整數N,(1<= N <= 100).表示包含N個測試樣例. 
每個測試樣例由兩個字符串A,B( 0< strlen(A),strlen(B) <= 1000) 和一個整數n( 0 <= n <= 1000)構成.
對於每個測試樣例,輸出Not Smaller 或 Smaller.


Sample Input


3
acedsd
acdd
2
eedfd
zzxxxx
3
feefs
as
1
      

Sample Output


Not Smaller
Smaller
Not Smaller
 
用二維數組記錄a長度爲i,b長度爲j時最長公共子串的長度。maze[i][j]的更新方式有兩種情況:①a[i] == b[i],此時maze[i][j] =max(maze[i - 1][j] , maze[i][j - 1] ,  maze[i - 1][j - 1] + 1);②a[i] != b[i],此時maze[i][j] = max(maze[i - 1][j] , maze[i][j - 1] , maze[i - 1][j - 1]).以下舉例說明填充maze[i][j]的方法:

                      a       b       c     d
                 0   0       0       0      0
             a  0   1       1       1      1

             b  0   1       2       2      2

             e  0   1       2       2      2

             d  0   1       2       2      3

代碼:
<span style="font-size:14px;">#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"

using namespace std;

char a[1005],b[1005];
int maze[1005][1005];

int main()
{
    int cas;
    while(~scanf("%d",&cas))
    {
        int n;
        while(cas--)
        {
            scanf("%s%s%d",a,b,&n);
            int la = strlen(a);
            int lb = strlen(b);
            for(int i = 0;i <= la;i++)
            {
                for(int j = 0;j <= lb;j++)
                {
                    maze[i][j] = 0;
                }
            }
            for(int i = 1;i <= la;i++)
            {
                for(int j = 1;j <= lb;j++)
                {
                    if(a[i - 1] == b[j - 1])
                    {
                        maze[i][j] = maze[i - 1][j - 1] + 1; //a[i] == b[i]時,由對角線更新maze
                    }
                    else
                    {
                        maze[i][j] = max(maze[i - 1][j],maze[i][j - 1]); //a[i] != b[i]時,左下右上取較大
                    }
                }
            }
            if(maze[la][lb] >= n)
            {
                cout << "Not Smaller" << endl;
            }
            else
            {
                cout << "Smaller" << endl;
            }
        }
    }
    return 0;
}
</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章