Problem Link:
http://poj.org/problem?id=3187
Idea:
Using binomial coeff
Source:
int n, sum;
vector<int> a;
int c[10][10];
int main()
{
// calc binom coeff
c[0][0] = 1;
for (int i = 1; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j == 0) c[i][j] = 1;
else c[i][j] = c[i - 1][j] + c[i - 1][j - 1];
}
}
// take input
cin >> n >> sum;
for (int i = 1; i <= n; i++) {
a.push_back(i);
}
//store ans
vector<string> ans;
do {
int d = 0;
for (int i = 0; i < n; i++) {
d += c[n - 1][i] * a[i];
}
if (d == sum) {
string str = "";
for (int i = 0; i < n; i++) str += (char)(a[i] + 'a' - 1);
ans.push_back(str);
}
} while (next_permutation(a.begin(), a.end()));
sort(ans.begin(), ans.end());
for (int i = 0; i < n; i++)
{
cout << (ans[0][i] - 'a' + 1) << " ";
}
cout << endl;
return 0;
}
No comments:
Post a Comment