Description
现在有n个人要排成一列,编号为1->n 。但由于一些不明原因的关系,人与人之间可能存在一些矛盾关系,具体有m条矛盾关系(u,v),表示编号为u的人想要排在编号为v的人前面。要使得队伍和谐,最多不能违背k条矛盾关系(即不能有超过k条矛盾关系(u,v),满足最后v排在了u前面)。问有多少合法的排列。答案对10^9+7取模。
Input
输入文件名为count.in。
第一行包括三个整数n,m,k。
接下来m行,每行两个整数u,v,描述一个矛盾关系(u,v)。
保证不存在两对矛盾关系(u,v),(x,y),使得u=x且v=y 。
Output
输出文件名为count.out。
输出包括一行表示合法的排列数。
Sample Input
输入1: 4 2 1 1 3 4 2 输入2: 10 12 3 2 6 6 10 1 7 4 1 6 1 2 4 7 6 1 4 10 4 10 9 5 9 8 10
Sample Output
输出1: 18 输出2: 123120
Data Constraint
对于30%的数据,n<=10
对于60%的数据,n<=15
对应100%的数据,n,k<=20,m<=n*(n-1),保证矛盾关系不重复。
Source / Author: 翁文涛
题解:
状压dp。
设f[s][j]表示选人的状态为s,已经用了j次违背机会的方案数。
就是答案
考虑转移
对于f[i][j],先枚举一个k使得k不在i中。
若加上k这个点没有违背任何要求,f[i][j] - > f[i & (1<<(k-1))][j]
若矛盾 f[i][j] - > f[i & (1<<(k-1))][j+tot] ,tot是违背数
重点是如何处理矛盾。
设fal[i] 是题目要求要排在i这个人后面的集合,
那么tot就是fal[i] & i中 1的个数(c++函数 : __builtin_popcount( int ))
O(2^n * k *n )
#include<bits/stdc++.h>
#define S 1048586
#define N 21
#define inf 2147483647
#pragma GCC optimize(3)
#define rint register int
#define point(a) multiset<a>::iterator
#define mod (int)(1e9+7)
#define mem(a,b) memset(a,b,sizeof (a))
#define open(x) freopen(x".in","r",stdin);freopen(x".out","w",stdout);
using namespace std;
int n,m,k,t,ans;
int fal[N],f[S][N];
int main()
{
open("count");
scanf("%d%d%d",&n,&m,&k);
rint i,j;
for(i=1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
fal[u]|=(1<<(v-1));
}
mem(f,0);
ans=0;
int s_tot=(1<<n);
f[0][0]=1;
for(i=0;i<s_tot;i++)
{
for(j=0;j<=k;j++)if(f[i][j])
{
for(rint now=1;now<=n;now++)
{
int s=(1<<(now-1));
if((s & i) ==0)
{
int tot=__builtin_popcount(fal[now] & i);
if(j+tot<=k)(f[i | s][j+tot]+=f[i][j])%=mod;
}
}
}
}
for(i=0;i<=k;i++)(ans+=f[s_tot-1][i])%=mod;
printf("%d\n",ans);
}
可过。