Let be the number of ways to deal cards to teachers arranged in a line (the first and the last are not considered adjacent). This problem is equivalent to counting binary sequences of length consisting of s and s in which no two s are adjacent. The solution is given by the Fibonacci sequence defined by the following recurrence relation:
Let be the number of ways to deal cards to teachers seated in a circle.
If the first teacher does not receive an ace, then the remaining n - 1 teachers can be dealt aces in g(n - 1) ways.
If the first teacher does receive an ace, then the second and the last teachers must not receive aces. In this case, the remaining n - 3 teachers can be dealt aces in g(n - 3) ways.
Thus, we obtain the following relation:
Example
For n = 3, we need the value . It can be found from the equality g(0) + g(1) = g(2), which gives
Therefore,
The base cases are as follows:
Algorithm implementation
Declare an array to store the Fibonacci numbers.
#define MAX 46
int fib[MAX];The main part of the program. Compute the Fibonacci numbers.
fib[0] = 1; fib[1] = 2;
for (int i = 2; i < MAX; i++)
fib[i] = fib[i - 1] + fib[i - 2];Read the input number .
scanf("%d", &n);Compute the answer .
if (n == 1) res = 2; else
if (n == 2) res = 3; else
res = fib[n - 1] + fib[n - 3];Print the answer.
printf("%d\n", res);Java implementation
import java.util.*;
public class Main
{
private static final int MAX = 46;
public static void main(String[] args)
{Declare an array to store the Fibonacci numbers.
int[] fib = new int[MAX];Compute the Fibonacci numbers.
fib[0] = 1;
fib[1] = 2;
for (int i = 2; i < MAX; i++)
fib[i] = fib[i - 1] + fib[i - 2];Read the input number .
Scanner con = new Scanner(System.in);
int n = con.nextInt();Compute the answer .
int res;
if (n == 1) res = 2;
else if (n == 2) res = 3;
else res = fib[n - 1] + fib[n - 3];Print the answer.
System.out.println(res);
}
}Python implementation
Declare a list to store the Fibonacci numbers.
fib = [0] * 46Compute the Fibonacci numbers.
fib[0] = 1
fib[1] = 2
for i in range(2, 46):
fib[i] = fib[i - 1] + fib[i - 2]Read the input number .
n = int(input())Compute the answer .
if n == 1: res = 2
elif n == 2: res = 3
else: res = fib[n - 1] + fib[n - 3]Print the answer.
print(res)