UVALive 4844 String Popping【记忆化搜索】

题目大意:

给定一个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;
}


你可能感兴趣的:(UVALive 4844 String Popping【记忆化搜索】)