动态规划专项intermediate:UVa 10981

来源:互联网 发布:ubuntu更新火狐浏览器 编辑:程序博客网 时间:2024/05/16 09:28

直接用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;}


原创粉丝点击