您的位置:首页 > 其它

hdu3811 Permutation (状态压缩DP)

2015-11-23 23:48 375 查看
题目点我点我点我

题目大意:题目给出m对 a b,表示a位置放b,问你满足其中至少一对关系的总排列数。

思路:表面上看似容斥定理,至于行不行我也没试过,用状态压缩DP就奇快,dp[i]记录的是第i种状态不符合a位置放b的情况的数目,dp[(1<

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define inf 0x3f3f3f3f
long long dp[1<<18];
long long per[18]={0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000};
//当长度为N时有N!种排列情况,把N!用数组a存
int flag[18][18];
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);

int t,n,m,a,b,cas=1;
scanf("%d",&t);
while(t--)
{
memset(dp,0,sizeof(dp));
memset(flag,0,sizeof(flag));
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
a--;b--;
flag[a][b]=1;    //用flag记录a位置不能选择b
}
dp[0]=1;
for(int i=0;i<n;i++)
{
for(int j=(1<<n)-1;j>=0;j--)
{
if(!dp[j])continue;
for(int k=0;k<n;k++)
{
if((j&(1<<k))!=0)continue; //j状态已有数字k了
if(flag[i][k]==1)continue; //k位置不能放i
dp[j|(1<<k)]+=dp[j];
}
}
}
printf("Case %d: %lld\n",cas++,per
-dp[(1<<n)-1]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: