pku 3087 Shuffle'm Up 说的是bfs,其实就是个模拟

http://poj.org/problem?id=3087

刚看到题目的时候给我整蒙了,BFS怎么做啊?这不就是模拟一下洗牌的过程,如果遇到目标字符串就输出步数,如果回到原始串,就说明到不了目标串。

View Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

char aim[207];//目标串
int n;

struct node
{
    char s1[107];
    char s2[107];
    int len;
};
bool isok(char *s,int start)//检查串
{
    for (int i = start, j = 0; j < n; ++j,++i)
    {
        if (aim[i] != s[j]) return false;
    }
    return true;
}
int bfs(char *s1,char *s2)
{
    node s;
    queue<node>q;
    strcpy(s.s1,s1);
    strcpy(s.s2,s2);
    s.len = 0;
    q.push(s);
    int sum = -1;
    bool flag = false;//拥有标记不是初始串
    //int test  = 10;
    while (!q.empty())
    {
        node cur = q.front(); q.pop();
        if (isok(cur.s1,0) && isok(cur.s2,n))//找到目标串
        {
            sum = cur.len;
            break;
        }
        if (flag && !strcmp(cur.s1,s1) && !strcmp(cur.s2,s2))  break;//回到原始串
        flag = true;
        char str[207];
        int i = 0;
        int l = 0;
        node tt;
        for (i = 0; i < n; ++i)
        {
            str[l++] = cur.s2[i];
            str[l++] = cur.s1[i];
        }
        str[l] = '\0';
        //printf(">>>>>%s\n",str);
        for (i = 0; i < n; ++i)  tt.s1[i] = str[i];
        tt.s1[n] = '\0';
        for (i = n; i < 2*n; ++i) tt.s2[i - n] = str[i];
        tt.s2[n] = '\0';
        //printf(">>>>>%s %s %s\n",str,tt.s1,tt.s2);
        tt.len = cur.len + 1;
        q.push(tt);
    }
    return sum;
}
int main()
{
    char s1[107],s2[107];
    int t,cas = 1;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d",&n);
        scanf("%s%s",s1,s2);
        scanf("%s",aim);
        int flag = bfs(s1,s2);
        printf("%d %d\n",cas++,flag);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值