POJ 3087 Shuffle'm Up【深搜】

题目链接

题目意思

就类似于我们玩的纸牌洗牌游戏,有两个字符串,现在两个字符串中的字符一个插一个,然后再分为两半,接着进行洗牌工作,如果能够洗到给定的字符串就输出最少的洗牌次数,否则输出-1。

解题思路

就用深搜来写,我们每次用两个新的字符串在存储洗牌后的两个字符串,用深搜一直去找,知道能够找到给定的字符序列,如果中间出现了循环就直接结束输出-1。

代码部分
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <map>
using namespace std;
string s1,s2,s12;
int n;
map<string,int>M;
int dfs(string s1,string s2,int step)
{
    string c1,c2,c12;
    c12=s1+s2;
    if(M[c12]==1)///如果出现过开始循环
        return -1;
    if(c12==s12)
    {
        return step;
    }
    M[c12]++;
    int k=0;
    for(int i=0; i<n; i++)
    {
       if(k<n)
        c1+=s2[i];
       else
        c2+=s2[i];
       k++;
       if(k<n)
        c1+=s1[i];
       else
        c2+=s1[i];
       k++;
    }
    return dfs(c1,c2,step+1);
}
int main()
{
    int t;
    scanf("%d",&t);
    int cas=1;
    while(t--)
    {
        scanf("%d",&n);
        cin>>s1>>s2>>s12;
        M.clear();
        int ans=dfs(s1,s2,0);
        cout<<cas++<<" "<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值