Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.
The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge.
When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).
The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1.
It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.
Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).
5 -1 -1 4 3 -1
2
/*
题意:N个位置,有些位置已经填上数字,有些位置为-1表未填数字,现在需要把1~N中除了已经填了的数字外
的数字填入余下空位并保证A[i]!=i,问有多少填法(MOD 1e9+7)
思路: 错排。有些位置的数字已经用掉了这些位置可以随便填数字,计这样的位置有m个,另外一些位置它所
对应的数字还没有用掉需要错排,计这样的位置有n个。
1.在这n个位置中可以全部用所对应的数字进行错排,这样得到递推式是 D[i]=(i-1)*(D[i-1]+D[i-2])。
2.此外,也可以把可以随便排的数字(也为m个)加入进来排,就是在加入第i个数字的时候,
加入可以随便排的数字(属于m中一员,不属于n中的一员),可以得到递推式D[i]=m*D[i-1]。
这样,总的递推式 D[i]=(i-1)*(D[i-1]+D[i-2])+m*D[i-1]。
n个不能随便填的位置填好了,再处理m个能随便填的位置,结果是m!
最终结果就是D[n]*m!
*/
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define maxn 2005
#define MOD 1000000007
__int64 N[maxn];
__int64 D[maxn];
void get_N(__int64 x) //阶乘初始化
{
N[0]=1;
for(int i=1;i<x;i++)
{
N[i]=(N[i-1]*i)%MOD;
}
}
int n1;
bool vis[maxn];
int main()
{
get_N(maxn);
while(~scanf("%d",&n1))
{
memset(vis,0,sizeof(vis));
int x;
int cnt1=0,cnt2=0;
int m;
int n;
for(int i=1;i<=n1;i++)
{
scanf("%d",&x);
if(x!=-1)
{
cnt2++;
vis[x]=1;
vis[i]=1;
}
}
for(int i=0;i<maxn;i++)
if(vis[i])cnt1++;
m=cnt1-cnt2;
n=n1-cnt1;
memset(D,0,sizeof(D));
D[0]=N[m];
D[1]=m*D[0];
for(int i=2;i<=n;i++)
{
D[i]=(((i-1)*(D[i-1]+D[i-2])%MOD)+(m*D[i-1])%MOD)%MOD;
}
printf("%I64d\n",D[n]);
}
}