POJ 3087 Shuffle'm Up(BFS)

44 篇文章 0 订阅
39 篇文章 0 订阅

很多人不觉得这是个搜索,说是模拟,其实这是没有理解搜索的实质。

搜索就是扩充状态和状态的转移。   该题可以将每次洗牌后的情况当成状态进行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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值