动态规划专项intermediate:UVa 10981

直接用map记录状态,1表示该状态可以达到目标状态,0表示不能。然后从左到右dfs,然后一旦得到的返回值为1,就记录路径,然后返回。记录路径也可以用map来实现。本来以为用stl会很慢,结果也只跑了19ms。

#include <iostream>
#include <cstdio>
#include <map>
#include <string>
using namespace std;
string s,t;
map<string,int> dp;
map<string,string> path;
int dfs(string st)
{
    if(dp.count(st)) return dp[st];
    if(st.size()==t.size())
    {
        if(st==t) return 1;
        else return 0;
    }
    for(int i=0;i<st.size()-1;i++)
    {
        string tmp,t=st;
        if(st[i]=='a'&&st[i+1]=='a') tmp='b';
        if(st[i]=='a'&&st[i+1]=='b') tmp='b';
        if(st[i]=='a'&&st[i+1]=='c') tmp='a';
        if(st[i]=='b'&&st[i+1]=='a') tmp='c';
        if(st[i]=='b'&&st[i+1]=='b') tmp='b';
        if(st[i]=='b'&&st[i+1]=='c') tmp='a';
        if(st[i]=='c'&&st[i+1]=='a') tmp='a';
        if(st[i]=='c'&&st[i+1]=='b') tmp='c';
        if(st[i]=='c'&&st[i+1]=='c') tmp='c';
        if(dfs(t.replace(i,2,tmp)))
        {
            path[st]=t;
            return dp[st]=1;
        }
    }
    return dp[st]=0;
}
void print(string st)
{
    cout<<st<<endl;
    if(st!=t) print(path[st]);
}
int main()
{
    freopen("in.txt","r",stdin);
    int T;
    cin>>T;
    while(T--)
    {
        dp.clear();
        path.clear();
        cin>>s>>t;
        if(s.size()<t.size()) cout<<"None exist!"<<endl;
        else
        {
            if(!dfs(s)) cout<<"None exist!"<<endl;
            else
            {
                print(s);
            }
        }
        if(T) cout<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值