很多人不觉得这是个搜索,说是模拟,其实这是没有理解搜索的实质。
搜索就是扩充状态和状态的转移。 该题可以将每次洗牌后的情况当成状态进行BFS,只不过这个BFS每次只有一个决策可以拓展罢了,这样当出现状态重复时将无解。
那么为什么要用BFS呢? 因为循环结的周期未知,用BFS可以减少递归的无目的性。 而且该题比较简单,每层只有一个拓展点,所以用什么方法倒也无所谓。
关于对状态的判重,可以用HASH,但是该题数据较水,直接map即可。
细节参见代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int INF = 1e9;
const int maxn = 1000 + 5;
int n,m,T,kase = 0;
string s1,s2,s;
struct node{
int cnt;
string s;
};
map<string, int > p;
int bfs(node start) {
queue<node> q;
p.clear();
q.push(start);
while(!q.empty()) {
node u = q.front(); q.pop();
if(u.s == s && u.cnt != 0) return u.cnt;
node v;
for(int i=0;i<n;i++) {
v.s += u.s[n+i];
v.s += u.s[i];
}
if(!p.count(v.s)) {
p[v.s] = 1;
v.cnt = u.cnt+1;
q.push(v);
}
}
return -1;
}
int main() {
scanf("%d",&T);
while(T--) {
cin>>n>>s1>>s2>>s;
node u ; u.s = s1 + s2;
u.cnt = 0;
int ans = bfs(u);
printf("%d %d\n",++kase,ans);
}
return 0;
}