POJ-3087 Shuffle'm Up 【暴力+STL】

版权声明:本文为博主原创文章,转载请注明出处( • ̀ω•́ )✧ https://blog.csdn.net/wangws_sb/article/details/83446654

题目传送门

题目:t组数据,给出长度为n的初始字符串s1,s2,和长度为2n的目标字符串p,按题目要求操作,问s1,s2达到字符串p的最小操作数,若达不到则输出-1;输出时首先输出数据组数。

题解:直接用字符串模拟,用map记录该状态是否被访问过,如果被访问过则说明出现循环,到达不了目标状态。

补充:用map<string,int> mp;记录某一状态是否被访问过;

string中的s.substr(int a,int n)函数:从s字符串复制一个从a位置开始,并具有n长度的子字符串

AC代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define inf 0x3f3f3f
typedef long long ll;
const int mod=1e9+7;
const int maxn=1e5+7;
int t,n;
string s1,s2,s,p;
map <string,int> mp;
int main()
{
    io;
    cin>>t;
    for(int o=1;o<=t;o++)
    {
        cin>>n;
        cin>>s1>>s2>>p;
        int ans=0;
        while(1)
        {
            ans++;
            s="";
            for(int i=0;i<n;i++)
                s=s+s2[i]+s1[i];
            if(mp[s])
            {
                ans=-1;
                break;
            }
            else if(s==p)
            {
                break;
            }
            else
            {
                mp[s]=1;
                s1=s.substr(0,n);
                s2=s.substr(n,n);
            }
        }
        cout<<o<<" "<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wangws_sb/article/details/83446654