poj 3087 bfs 洗牌

本文深入解析了POJ-3087问题的解决方案,使用BFS算法进行字符串操作,并通过自定义结构体和排序规则实现状态记录,避免重复搜索,最终求解出字符串拼接问题的最小步数。

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

POJ - 3087

 

用set的时候写错了。以后还是注意一下当容器中的元素类型为结构体类型时,写出排序规则。先这样记。

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<queue>
#include<string>
#include<set>
using namespace std;
string str1,str2,str3;
int c;
int ans;
struct node
{
    string s1,s2;
    int step;
    bool operator <(const node &t1) const{
        return s1<t1.s1;
    }
};
///当容器中的元素类型为结构体类型时,必须写出排序规则
set<node> se;
set<node>::iterator it;
void bfs(node s)
{
    queue<node> q;
    q.push(s);
    se.insert(s);
    while(!q.empty())
    {
        node now=q.front();
        q.pop();
        if(now.s1+now.s2==str3)
        {
            ans=now.step;
            break;
        }
        else
        {
            string ss;
            for(int i=0;i<c;i++)
            {
                ss+=now.s2[i];
                ss+=now.s1[i];
            }
            node next;
            next.s1=ss.substr(0,c);
            next.s2=ss.substr(c);
            next.step=now.step+1;
            for(it=se.begin();it!=se.end();it++)
            {
                if((*it).s1==next.s1&&(*it).s2==next.s2)
                    break;
            }
            if(it==se.end())
            {
                q.push(next);
                se.insert(next);
            }
        }
    }
}
int main()
{
//    freopen("in.txt","r",stdin);
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
//        se.clear();
        ans=-1;
        cin>>c;
        cin>>str1>>str2>>str3;
        node w;
        w.s1=str1;
        w.s2=str2;
        w.step=0;
        bfs(w);
        cout<<i<<" ";
        if(ans==-1)
            cout<<-1<<endl;
        else
            cout<<ans<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值