题目:
李白打酒
话说大诗人李白,一生好饮。幸好他从不开车。
一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:
无事街上走,提壶去打酒。
逢店加一倍,遇花喝一斗。
这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。
请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。
思路1:0表示店,1表示花,全排列并判断.(注意,14个数的全排列有14!中,自己写的一般全排列函数可能算不出来,可以用内置的next_permutation,不会重复排列,很快就可以算出来)
代码1:
#include <bits/stdc++.h>
using namespace std;
int an[15]={0,0,0,0,0,1,1,1,1,1,1,1,1,1,1};
long res(0);
bool judge()
{
long sta = 2;
for(int i=0;i<15;++i) {
if(an[i]==0) sta *= 2;
else if(an[i]==1) sta -= 1;
}
if(sta==0) return true;
return false;
}
void print()
{
for(int i=0;i<15;++i) {
if(an[i]==0) cout << "a";
if(an[i]==1) cout << "b";
}
cout << endl;
}
int main()
{
do {
print();
if(judge()){
res += 1;
}
}while(next_permutation(an,an+14));
cout << res << endl;
return 0;
}
思路2:dfs,15个空,要么店要么花,一直走,走到尽头就判断。
#include <bits/stdc++.h>
using namespace std;
char ac[15];
long res(0);
void print()
{
printf("%s\n",ac);
}
void dfs(int i, int store, int flower, int wine)
{
if(store>5||flower>10||wine<0) return;
else if(store==5&&flower==10&&i==15) {
if(ac[14]=='b'&&wine==0) {
print();
res += 1;
}
return;
}
ac[i] = 'a';
dfs(i+1,store+1,flower,wine*2);
ac[i] = 'b';
dfs(i+1,store,flower+1,wine-1);
}
int main()
{
dfs(0,0,0,2);
cout << res << endl;
return 0;
}