ken_love_rin's blog

By ken_love_rin, history, 9 years ago, In English

Give an integer N (N<=5000). How many different premutations of sequence 1..n (p[1],p[2]...p[n]) so that p[i]<>i with 1<=i<=n. It means the i-th number in a permutation must be different with its index.

for example

input 2 output 1 (2,1)

input 3 output 2 {(2,3,1); (3,1,2)}

input 4 output 9

Can you give me a solution. thank you very much and sorry about my bad english. :)

  • Vote: I like it
  • -8
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

from total permutations, subtract number of wrong permutations

»
9 years ago, # |
  Vote: I like it +15 Vote: I do not like it

Such permutations are called derangements. I believe there is plenty of information about them in the internet.

»
9 years ago, # |
  Vote: I like it +5 Vote: I do not like it

a[0] = 1

а дальше так: a[n]=(-1)^n + n*a[n-1]

Илиментарная закономерность же, сразу в глаз бросается!!