I just find a problem like this
“Give you N different integers, do you know how many different sequences that the difference between every adjacent pair of numbers is larger than 1?”
And when the integers are “1 2 3”, then the answer is zero, when the integers are “5 3 1”, then the answer is 6, for “1 3 5” “1 5 3” “3 1 5” “3 5 1” “5 1 3” “5 3 1” satisfy the problem, I just tried all I could do but I couldn’t solve it, so my question is, how to write a algorithm to solve it.
Thankyou.
Here is my program
int n;bool vi[30];int a[30];int b[30];int counter = 0;
void dfs(int k)
{
if ( k == n)
{
for (int i = 2; i <= n; i ++)
if (fabs(b[i] - b[i - 1]) <= 1) return ;
counter ++;
return ;
}
for (int i = 0; i < n; i ++)
{
if (!vi[i])
{
b[k + 1] = a[i];
vi[i] = true;
dfs(k + 1);
vi[i] = false;
}
}
}
int main (void)
{
cin >> n;
for (int i = 0; i < n; i ++)
cin >> a[i];
memset(vi, 0, sizeof(vi));
for (int i = 0; i < n; i ++)
{
vi[i] = true;b[1] = a[i];dfs(1);vi[i] = false;
}
cout << counter << endl;
return 0;
}
The answer to the question, “How many different sequences are there…” can be solved without enumerating every combination. Which is a good thing, because
25!is approximately 1.55 x 10^24, or way more than any existing computer is going to enumerate in a second. Or in a year.This is a math problem, specifically combinatorics. See http://en.wikipedia.org/wiki/Combinatorics and possibly http://en.wikipedia.org/wiki/Combinations for information on how you would go about solving the problem.