hdu6170

HDU6170 Two strings

題目鏈接
題意是給兩個串,第一個串是隻包括大小寫字母的串,第二個串除了大小寫字母還包含了 ” * ” “.” 。 “.”可以匹配任意字符 ,“ * ”可以讓前面的字符出現任意次,包括0次。 問這兩個串能不能匹配上。
這道題有很多種解法,用java正則或者模擬或者dp都行。
給出dp做法,dp[i][j][0/1/2]代表第一串前i個和第二串前j個且第二個串能否匹配上,[0/1/2]分別代表第二個串第j個字符爲*時,使前面第一個字符出現超過1次/1次/0次 ,然後就可以dp轉移了

 #include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<set>
#include<map>
#include<time.h>
#include<cstdio>
#include<vector>
#include<list>
#include<stack>
#include<queue>
#include<iostream>
#include<stdlib.h>
using namespace std;
#define  LONG long long
const LONG  INF=0x3f3f3f3f;
const LONG  MOD=1e9+7;
const double PI=acos(-1.0);
#define clrI(x) memset(x,-1,sizeof(x))
#define clr0(x) memset(x,0,sizeof x)
#define clr1(x) memset(x,INF,sizeof x)
#define clr2(x) memset(x,-INF,sizeof x)
#define EPS 1e-10
#define lson  l , mid , rt<< 1
#define rson  mid + 1 ,r , (rt<<1)|1
#define root 1, n , 1
bool dp[2650][2600][3] ;
char str1[2510]  ;
char str2[2510] ;
int main()
{
    int T ;
    cin >> T ;
    while(T --)
    {
        str1[0] = str2[0] = '#' ;
        scanf("%s%s",str1 + 1,str2+1) ;
        int n = strlen(str1) - 1;
        int m = strlen(str2) - 1;
        clr0(dp ) ;
        dp[0][0][0] = 1;
        dp[0][0][1] = 1;
        dp[0][0][2] = 1;
        for(int i = 0 ; i<= n ; ++ i )
        {
            for(int j = 0 ; j<= m ; ++ j )
            {
                if(str2[j]== '.')
                {
                    dp[i][j][0] |= ( dp[i-1][j-1][0] |dp[i-1][j-1][1]|dp[i-1][j-1][2] )  ;
                    dp[i][j][1] = dp[i][j][0] ;
                    dp[i][j][2] = dp[i][j][0] ;
                }
                else if(str2[j] != '*')
                {
                    if(str1[i] == str2[j])
                        dp[i][j][0] |= ( dp[i-1][j-1][0] |dp[i-1][j-1][1]|dp[i-1][j-1][2] )  ;
                    dp[i][j][1] = dp[i][j][0] ;
                    dp[i][j][2] = dp[i][j][0] ;
                }
                else
                {
                    if( i>=1&&str1[i-1] == str1[i] )
                        dp[i][j][0] |=(dp[i-1][j][0]),
                    dp[i][j][0] |= (dp[i-1][j-1][0] | dp[i-1][j-1][1] | dp[i-1][j-1][2]) ;
                    dp[i][j][1] |= (dp[i][j-1][0]|dp[i][j-1][1]|dp[i][j-1][2]) ;
                    dp[i][j][2] |= (dp[i][j-2][0] | dp[i][j-2][1] | dp[i][j-2][2] ) ;
                }
            }
        }
        int ans = (dp[n][m][0] | dp[n][m][1] | dp[n][m][2] ) ;
        if(ans)
            cout<<"yes"<<endl;
        else cout<<"no"<<endl;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章