題目大意:
給定一個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;}