Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=3811
Title: Given the number of 1~n, the total number of permutations that satisfy at least one condition is obtained. The m conditions are as follows: The number of AI positions is bi
Analysis: The total number of permutations satisfying at least one condition is calculated indirectly by finding out the total number of permutations that a condition does not satisfy.
Dp[n][state] indicates that the first n bits are not the number of perfectly arranged states. The state transition equation is:
Dp[i+1][j| ( 1<<k)]+=dp[i][j]; here, use a scrolling array to optimize the next space, or MLE.
#include <cstdio>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#include<queue>#include<cstdlib>#include<vector>#include<Set>#include<map>#defineLL Long Long#defineMoD 1000000007#defineINF 0x3f3f3f3f#defineN 50010using namespacestd; LL dp[2][1<< -],f[ -];intvis[ -][ -];voidinit () {f[1]=1; for(intI=2; i<= -; i++) f[i]=i*f[i-1];}intMain () {intt,n,m,x,y,cas=1; Init (); scanf ("%d",&t); while(t--) {memset (Vis,0,sizeof(VIS)); scanf ("%d%d",&n,&m); for(intI=1; i<=m;i++) {scanf ("%d%d",&x,&y); X--;y--; Vis[x][y]=1;//mark, x position cannot select Y} memset (DP,0,sizeof(DP)); for(intI=0; i<n;i++)if(!vis[0][i]) dp[0][1<<i]=1;//If the 1th bit is not a perfect arrangement, the arrangement value starting with that number is 1 intCur=0, nxt=1; for(intI=0; i<n-1; i++) { for(intJ= (1<<n)-1; j>=0; j--) { if(Dp[cur][j]) for(intk=0; k<n;k++) { if(j& (1<<K))Continue;//The number k can only occur once if(vis[i+1][K])Continue;//This is the first i+1, not K .Dp[nxt][j| (1<<K)]+=Dp[cur][j]; //The J state becomes the permutation number produced by the P state, and the P state is the state after K is selected in the J-State i+1 position.}} swap (nxt,cur); } //F[n] means n! , that is, the entire arrangement of n number, minus the number of permutations that do not meet the conditions, that is, the request. //dp[n-1][(1<<n)-1] Indicates the total number of permutations that do not satisfy the condition, where (1<<n)-1 corresponds to the binary each of the first n bits of each is 1//that is, n numbers are already selected in that State .printf"Case %d:%i64d\n", cas++,f[n]-dp[cur][(1<<n)-1]); }}View Code
hdu3811 (State compression DP)