Problem Description
In combinatorics a permutation of a set S with N elements is a listing of the elements of S in some order (each element occurring exactly once). There are N! permutations of a set which has N elements. For example, there are six permutations of the set {1,2,3}, namely [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
But Bob think that some permutations are more beautiful than others. Bob write some pairs of integers(Ai, Bi) to distinguish beautiful permutations from ordinary ones. A permutation is considered beautiful if and only if for some i the Ai-th element of it is Bi. We want to know how many permutations of set {1, 2, ...., N} are beautiful.
Input
The first line contains an integer T indicating the number of test cases.
There are two integers N and M in the first line of each test case. M lines follow, the i-th line contains two integers Ai and Bi.
Technical Specification
1. 1 <= T <= 50
2. 1 <= N <= 17
3. 1 <= M <= N*N
4. 1 <= Ai, Bi <= N
Output
For each test case, output the case number first. Then output the number of beautiful permutations in a line.
Sample Input
3
3 2
1 1
2 1
3 2
1 1
2 2
4 3
1 1
1 2
1 3
Sample Output
Case 1: 4
Case 2: 3
Case 3: 18
Author
hanshuai
Source
The 6th Central China Invitational Programming Contest and 9th Wuhan University Programming Contest Preliminary
又是一题状态dp……当年比赛的时候RE到死没出来,今天1Y……rp咩?
#include <stdio.h>
#include <string.h>
int map[20][20];
long long dp[1<<18];
long long fact[18];
int main()
{
int i,j,n,T,m,x,y,p,k,cnt;
scanf("%d",&T);
fact[0]=1;
for (i=1;i<18;i++)
{
fact[i]=fact[i-1]*i;
}
cnt=1;
while(T--)
{
scanf("%d%d",&n,&m);
memset(map,0,sizeof(map));
for (i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
x--;
y--;
map[x][y]=1;
}
memset(dp,0,sizeof(dp));
dp[0]=1;
for (i=0;i<n;i++)
{
for (j=(1<<n)-1;j>=0;j--)
{
if (dp[j]==0) continue;
for (k=0;k<n;k++)
{
if ((j & (1<<k))!=0) continue;
if (map[i][k]==1) continue;
p=(j | (1<<k));
dp[p]+=dp[j];
}
}
}
printf("Case %d: %I64d\n",cnt++,fact[n]-dp[(1<<n)-1]);
}
return 0;
}