传送门 | 难度 |
---|---|
https://www.luogu.com.cn/problem/P1118 | 普及/提高- |
分析
不难发现,本题存在着一个杨辉三角。在此基础上进行暴力搜索,注意剪枝,即可通过。
AC代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int yh[15][15];
int n, sum, yhn;
bool flag[15];
int res[15];
bool mark = false;
void buildyh(int line) {
yh[0][1] = 1;
yh[1][1] = 1;yh[1][2] = 1;
for (int i = 2; i <= line; ++i) {
yh[i][1] = 1;
for (int j = 1; j <= i + 1; ++j) {
yh[i][j] = yh[i - 1][j - 1] + yh[i - 1][j];
}
}
}
void dfs(int c,int s) {
if (mark)
return;
if (c == n + 1) {
if (s == sum) {
//for (int i = 1; i < n; ++i) {
// printf("%d ", res[i]);
//}
//printf("%d\n", res[n]);
mark = true;
return;
}
return;
}
if (s >= sum) {
return;
}
for (int i = 1; i <= n; ++i) {
if (mark)
return;
if (flag[i])
continue;
flag[i] = true;
res[c] = i;
dfs(c + 1, s + i * yh[yhn][c]);
flag[i] = false;
}
}
int main() {
scanf("%d%d", &n, &sum);
yhn = n - 1;
buildyh(yhn);
dfs(1, 0);
if (!mark)
return 0;
for (int i = 1; i < n; ++i) {
printf("%d ", res[i]);
}
printf("%d\n", res[n]);
return 0;
}