您的位置:首页 > 其它

动态规划专项intermediate:UVa 10981

2013-05-05 21:00 309 查看
直接用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: