POJ 3087 Shuffle'm Up

本文提供了一道来自POJ平台的题目3087的解答思路及AC代码。题目要求判断通过操作能否将初始字符串转换为目标字符串。采用模拟的方法并利用哈希表记录状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出两个字符串,d2字符串在下,d1字符串在上,交叉组成一个字符串,判断初始串进行若干次操作后是否能到目标串

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

思路:模拟即可

注意点:需要记录该位置是否到达过,用map作为hash即可


以下为AC代码:

Run IDUserProblemResultMemoryTimeLanguageCode LengthSubmit Time
13917619luminous113087Accepted772K0MSG++1802B2015-02-27 22:50:10
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define ll long long
#define ull unsigned long long
#define all(x) (x).begin(), (x).end()
#define clr(a, v) memset( a , v , sizeof(a) )
#define pb push_back
#define mp make_pair
#define read(f) freopen(f, "r", stdin)
#define write(f) freopen(f, "w", stdout)
using namespace std;
//const double pi = acos(-1);
//const double eps = 1e-10;
//const int dir[[4][2] = { 1,0, -1,0, 0,1, 0,-1 };
map< string, int > vis;
int m;
string a, b;
string c;
void init()
{
    vis.clear();
    cin >> m >> a >> b >> c;
}
int solve()
{
    queue<string> q;
    string tmp;
    tmp.resize( 2 * m );
    for ( int i = 0; i < m; i ++ ){
        tmp[2*i] = b[i];
        tmp[2*i+1] = a[i];
    }
    q.push ( tmp );
    vis[tmp] = 1;
    while ( ! q.empty() ){
        tmp = q.front();
        q.pop();
        string x ( tmp, 0, m );
        string y ( tmp, m, m );
        string k;
        k.resize( 2 * m );
        for ( int i = 0; i < m; i ++ ){
            k[2*i] = y[i];
            k[2*i+1] = x[i];
        }
        if ( vis[k] )
            return -1;
        if ( vis[k] == 0 ){
            vis[k] = vis[tmp] + 1;
            q.push ( k );
        }
        if ( k == c ){
            return vis[k];
        }
    }
}
int main()
{
    ios::sync_with_stdio( false );
    int t;
    cin >> t;
    for ( int i = 1; i <= t; i ++ ){
        init();
        cout << i << ' ' << solve() << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值