UVALive 4844 String Popping【記憶化搜尋】

來源:互聯網
上載者:User

題目大意:

給定一個a、b構成的字串,每次可以消去長度不小於2的連續相同字元,問給定字元能否消成空串。

思路:首先我的思路就是搜尋,當然暴搜的話逾時。然後我就想著記憶搜尋的狀態,讓狀態變少!

我記錄的狀態時:剩餘字母的數量和ab變成01後位元值,打包成pair

#include<cstdio>#include<cstring>#include<iostream>#include <map>#include <utility>using namespace std;char maps[30];bool vis[30],flag;int len;bool check(){    for(int i=0;i<len;i++)if(!vis[i])return false;    return true;}map < pair<int,long long> , int > mymap;void dfs(int pos){    if(flag)return;    if(pos>=len)return;    //m++;if(m%1000==0)cout<<m<<endl;    long long type = 0;    int tt = 0;    for(int i = 0;i < len;i++)        if(vis[i] == 0)        {            tt++;            //cout << maps[i];            if(maps[i] == 'a')                type = (type<<1) | 1;            else type = type<<1;        }    //cout << "\n";    pair <int ,long long>p(tt,type);    if(mymap[ p ] == 1) return;    int npos = pos;    while(npos < len)    {        while(vis[npos])npos++;        int cnt=0;        pos = npos;        for(;npos<len;npos++)        {            if(vis[npos])continue;            if(maps[npos]==maps[pos])cnt++;            else break;        }        if(cnt>=2)        {            bool _vis[26];            for(int i=pos;i<npos;i++) _vis[i]= vis[i];            for(int i=pos;i<npos;i++)vis[i]=true;            if(check())            {                flag=true;                return;            }            dfs(0);            for(int i=pos;i<npos;i++) vis[i]=_vis[i];        }        while(vis[npos])npos++;    }    mymap[ p ] = 1;}int main(){    int cas;    cin>>cas;    while(cas--)    {        memset(vis,0,sizeof(vis));        mymap.clear();        flag=false;        cin>>maps;        len=strlen(maps);        dfs(0);        if(flag) cout << 1;else cout << 0;        cout << "\n";    }    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.