可可口乐题解

//先打伪代码
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;
}

第一次发题解,不喜勿喷

12 个赞

image

8 个赞

题目名就叫可可口乐

6 个赞

666

6 个赞

对的题就叫可可口乐

5 个赞

屏幕截图 2023-07-14 154828

5 个赞

可可口乐

4 个赞

可可口乐

4 个赞

感谢大佬

4 个赞

没事

6 个赞

别回老贴

6 个赞

**别发呀

6 个赞

呵∑

4 个赞