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
题意:给定1~n个数,存在着n!种排列。m个条件如下:ai位置的数为bi,表示ai位置放bi,问你满足其中至少一对关系的总排列数。
思路:这道题的话,我们用状压DP来做,首先我们根据题意,设dp[i]为记录的是第i种状态下不符合ai位置放bi的情况的数目,
然后又因为n个数存在着n!种排列,所以我们用一个数组a表示所有的排列,最后我们用a[n]-dp[(1<<n)-1]即为所求答案。
AC代码:
#include <bits/stdc++.h>
typedef long long ll;
const int maxx=1010;
const int inf=0x3f3f3f3f;
using namespace std;
ll dp[1<<18];
ll a[maxx];
ll v[maxx][maxx];
void jc()
{
a[0]=1;
for(int i=1; i<=18; i++)
a[i]=i*a[i-1];
}
int main()
{
int t,ca=1;
scanf("%d",&t);
jc();
while(t--)
{
memset(dp,0,sizeof(dp));
memset(v,0,sizeof(v));
int n,m;
scanf("%d%d",&n,&m);
int ai,bi;
for(int i=1; i<=m; i++)
{
scanf("%d%d",&ai,&bi);
ai--;
bi--;
v[ai][bi]=1;
}
dp[0]=1;
for(int i=0; i<n; i++)
{
for(int j=(1<<n)-1; j>=0; j--)
{
if(dp[j]==0)
continue;
for(int k=0; k<n; k++)
{
if(j&(1<<k))
continue;
if(v[i][k])
continue;
dp[j|(1<<k)]+=dp[j];
}
}
}
printf("Case %d: %lld\n",ca++,a[n]-dp[(1<<n)-1]);
}
return 0;
}