POJ - 3087:Shuffle'm Up (字符串模拟)

一、内容

题意:给定2个字符串s1,s2,将2个字符串进行重组成S,规则是S2最下面拿一个,S1最下面拿1个,直到所有块都用完。

二、思路

  • 用map记录下S串结果,若以前访问过这个串代表不可能有结果直接返回-1
  • 然后就是模拟重组串的过程。

三、代码

#include<iostream>
#include<string>
#include<map>
using namespace std;
string End, s1, s2;
int N, C;
int f() {
    string tem = s1 + s2;
    map<string, bool>book;
    int step = 0;
    while (tem != End && !book[tem]) {
        book[tem] = true; step++;
        string newS = s1 + s2; int index = 0;
        for (int i = 0; i < C; ++i) {
            newS[index++] = tem[i + C];
            newS[index++] = tem[i];
        }
        tem = newS;
    }
    if (tem == End)return step;
    return -1;
}
int main() {
    freopen("in.txt", "r", stdin);
    cin >> N;
    for (int i = 1; i <= N; ++i) {
        cin >> C >> s1 >> s2 >> End;
        cout << i << " " << f() << endl;
    }
    return 0;
}
posted @ 2020-06-10 16:15  RioTian  阅读(133)  评论(0编辑  收藏  举报