蓝桥杯 算法训练
数字游戏
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 1e4 + 7;
typedef long long ll;
int n,sum,pt=1,getans = 0;
int used[12]={0};
int a[12];
int ans[12] = {0};
int flag =0;
void getsum(int j){//i²ãÊý sum×÷ΪºÍ
}
void dfs(int j,int num){//i×÷ΪµÚÒ»¸öÑ¡ÔñµÄÊý×Ö£¬ num±íʾµÚ¼¸¸öÊý×Ö
if(flag == 0){
if(num > n){
// for(int i = 1;i<=n;i++){
// cout<< ans[i]<<" ";
// }
// cout <<endl;
for(int i = 1;i<=n;i++){
a[i]=ans[i];
}
for(int j = 1;j<=n-1;j++){
for(int i = 1;i<=n-j;i++){
a[i]=a[i]+a[i+1];
}
}
//cout << a[1]<<endl;
if(a[1] == sum){
for(int i =1;i<=n;i++){
cout << ans[i] << " ";
}
cout <<endl;
flag =1;
}
//getsum(n-1);//µ÷ÓÃansÊý×é
return;
}
}
for(int i =1;i<=n;i++){
if(used[i]==0){
used[i]=1;
ans[num]=i;
dfs(i,num+1);
used[i]=0;
}
}
}
int main(){
cin >> n >> sum;
//n = 4,sum = 16;
//n = 4,sum = 22;
//n =10,sum =3844;
for(int i = 1;i<=n;i++){
if(flag == 1) break;
pt=1;
used[i]=i;
a[pt]=i;//±£´æÊý×é
ans[pt]=i;
dfs(i,2);
used[i]=0;
}
return 0;
}