HDOJ - 4545 魔法串 简单DP

来源:互联网 发布:淘宝最低价规则 编辑:程序博客网 时间:2024/05/22 14:32

     用二维bool记录可行的对应关系..为了处理方便..预处理所有的f[i][i]=true....

    dp[i]代表以b[i]为最后一个字符能匹配到a串的最大长度...


Program:

#include<iostream>#include<stdio.h>#include<cmath>#include<string.h>#include<algorithm>#include<queue>#include<stack>#define ll long long#define oo 1000007#define MAXN 1005using namespace std; char a[MAXN],b[MAXN];int dp[MAXN];bool f[26][26];int main(){           freopen("input.txt","r",stdin);   freopen("output.txt","w",stdout);         int T,t,i,j,m,la,lb;       bool ans;       char c1,c2;       scanf("%d",&T);       for (t=1;t<=T;t++)       {              scanf("%s%s%d",a+1,b+1,&m);              memset(f,false,sizeof(f));              for (i=0;i<26;i++) f[i][i]=true;              while (m--)              {                     do { c1=getchar(); } while (c1<'a' || c1>'z');                     do { c2=getchar(); } while (c2<'a' || c2>'z');                       f[c1-'a'][c2-'a']=true;              }              memset(dp,0,sizeof(dp));              la=strlen(a+1);     lb=strlen(b+1);              ans=false;              for (i=1;i<=lb;i++)                 for (j=0;j<i;j++)                    if (dp[i]<dp[j]+1 && f[b[i]-'a'][a[dp[j]+1]-'a'])                    {                           dp[i]=dp[j]+1;                           if (dp[i]==la)                           {                                 ans=true;                                 goto A;                           }                    }              A: ;              printf("Case #%d: ",t);              if (ans) printf("happy\n");                 else  printf("unhappy\n");       }       return 0;}