//先打伪代码
dfs(int step,int cnt){
if(剪枝){
return;
}
if(完成){
变化答案;
return;
}
for(i~7){
if(s[i]==t[step]){
swap(s[i],s[step];
dfs(step+1,cnt+1);
swap(s[i],s[step];
}
}}
//解释一下
/*
1. swap出现了两遍——因为swap的逆运算是swap
不逆运算不会变回原来的样子,就会cnt不++但是交换了;
2.cnt不能用全局变量;
cnt(1)
cnt(2)
假设到终点了
cnt(2)
cnt(1)
全局的话会乱成一团。
*/
#include <bits/stdc++.h>
using namespace std;
string s;
int n=8;
string t="cocacola";
int res=10;
void dfs(int step,int cnt)
{
if(cnt>=res){
return ;
}
if(step==7){
res=min(res,cnt);
return;
}
for(int j=step;j<n;j++){
if(s[j]==t[step]){
swap(s[j],s[step]);
dfs(step+1,cnt+(j!=step));
swap(s[j],s[step]);
}
}
}
int main()
{
cin>>s;
dfs(0,0);
cout<<res;
return 0;
}
第一次发题解,不喜勿喷
