hdu 4295 4 substrings problem DP 字串

來源:互聯網
上載者:User

題意:給定一個字串,還有它的四個字串, 選擇合適的位置讓這些子串覆蓋原串,問最多和最少的覆蓋字元數。

做法:先用個法子求出每個字元位置是否可以放某個串,然後建立狀態,dp[i][j],i是當前探索的位置,j是匹配點。值得注意的是,每個點可能可以匹配多個字串,這個可以用類似背包的手法解決,即在一個位置多次匹配計算修正,具體看代碼,其實數組是可以降成一維的

#include <cstdio>#include <cstring>#define max(a,b) ((a)>(b) ? (a):(b))#define min(a,b) ((a)<(b) ? (a):(b))#define eps 1e5const int sLEN=64;const int LMT=5000;const int lim=15;const int sub=4;int dpx[sLEN+10][lim+10],dpn[sLEN+10][lim+10];int can[LMT][sub];void init(void){    int i,j,k;    memset(can,0,sizeof(can));        for(j=0;j<70;j++)            for(k=0;k<70;k++)            {                dpx[j][k]=-eps;                dpn[j][k]=eps;            }            dpx[0][0]=dpn[0][0]=0;}int main(void){    char sec[LMT],ord[70];    int i,pos,ii,jj,j,st,t,anx,ann;    sec[0]=9;    while(~scanf("%s",&sec[1]))    {        init();        for(i=0;i<sub;++i)        {            scanf("%s",ord);            for(pos=1;sec[pos];++pos)            {                    for(ii=pos,jj=0;sec[pos]&&ord[jj]&&sec[ii]==ord[jj];++ii,++jj);                    if(!ord[jj])can[pos][i]=jj;            }        }        anx=-eps;ann=eps;        for(i=1;sec[i];++i)        {            for(j=0;j<=sLEN;++j)                for(st=0;st<=lim;++st)//0代表匹配位置在當前位置的後邊,當前位置增加1,匹配位置減少1,但0要另算                {                    if(j)                    {                        dpn[j][st]=dpn[j+1][st];                        dpx[j][st]=dpx[j+1][st];                    }                    else                    {                        dpn[j][st]=min(dpn[j][st],dpn[j+1][st]);                        dpx[j][st]=max(dpx[j][st],dpx[j+1][st]);                    }                }          for(t=0;t<sub;++t)//當前位置匹配一下。          if(can[i][t])            for(jj=0;jj<=sLEN;++jj)              for(st=0;st<=lim;++st)              if(!(st&(1<<t)))              {                  j=max(jj,can[i][t]);                  dpn[j][st|(1<<t)]=min(dpn[j][st|(1<<t)],dpn[jj][st]+max(0,j-jj));                  dpx[j][st|(1<<t)]=max(dpx[j][st|(1<<t)],dpx[jj][st]+max(0,j-jj));              }                anx=max(anx,max(dpx[1][lim],dpx[0][lim]));                ann=min(ann,min(dpn[1][lim],dpn[0][lim]));        }        printf("%d %d\n",ann,anx);    }    return 0;}

聯繫我們

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