7. 洗牌

原题链接:https://www.acwing.com/problem/content/description/4224/

#include<bits/stdc++.h>
using namespace std;

string a,b,c;
unordered_map<string,int> dist;
int n;

string sff(string a,string b)
{
    string c;
    for(int i=0;i<n;i++)
    {
        c+=a[i];
        c+=b[i];
    }
    return c;
}

void bfs()
{
    queue<string> q;
    string x=sff(b,a);
    dist[x]=1;
    q.push(x);
    while(q.size())
    {
        auto t=q.front();
        q.pop();
        if(t==c) return;
        string a,b;
        for(int i=0;i<n;i++) a+=t[i],b+=t[i+n];
        string c=sff(b,a);
        if(!dist.count(c)){
            dist[c]=dist[t]+1;
            q.push(c);
        }
    }
}
int main()
{
    int tt;
    scanf("%d",&tt);
    for(int i=1;i<=tt;i++)
    {
        dist.clear();
        cin>>n;
        cin>>a>>b>>c;
        bfs();
        if(!dist.count(c)) dist[c]=-1;
        printf("%d %d\n",i,dist[c]);
    }
}

posted on   skaman  阅读(17)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示