題意:給定一個n*n的矩陣,在矩陣中選n個數字(每行每列只能選一個數字),問選出的數字和>=m的方法數
思路:
設滿足條件的方案書爲ans, 總方案數爲 n!,那麼期望就是 n! / ans
1、矩陣較小可以狀壓
2、每次轉移以 數字和爲記錄,因爲m<=500,對於數字和>m,可以視爲m
dp[i][j][k] 表示前i件物品,在擺成二進制j狀態下 和爲k 的方法數
因爲對於第i個數,我們不需要關心前面i-1個數所在的各個位置,只需要知道他們佔了哪些位置
所以我們可以把dp簡化爲二維數組,dp[i][j] //在狀態i下 和爲j 的方法數
代碼如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#define pii pair<int, int>
using namespace std;
typedef long long ll;
const int N = 12;
int n, m;
int dp[5000][501]; //dp[i][j][k] 表示在擺成二進制j狀態下 和爲k 的方法數
int mp[N][N], Jie[20], Siz[13];
vector<int>G[13];
bool use[2][5000];
int GCD(int x,int y)
{
if(x > y)swap(x, y);
while(x)
{
y %= x;
if(x > y) swap(x, y);
}
return y;
}
int siz(int x)
{
int ans = 0;
while(x)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
int main()
{
int i, j;
Jie[0] = 1;
for(i = 1; i <= 12; i++) Jie[i] = Jie[i-1] * i;
for(i = 0; i <= 12; i++) G[i].clear();
for(i = 0; i < (1 << 12); i++) G[siz(i)].push_back(i);
for(i = 0; i <= 12; i++) Siz[i] = G[i].size();
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
scanf("%d", &mp[i][j]);
memset(dp, 0, sizeof(dp));
int top = 1, D = (1 << n);
dp[0][0] = 1;
for(i = 1, j = 0; i < D; i <<= 1, j++)
{
dp[i][min(m,mp[0][j])] = 1;
}
for(i = 1; i < n; i++)
{
for(j = 0; j < Siz[top]; j++)
{
int now = G[top][j]; //選top件物品中的某個狀態
if(now >= D) break;
for(int z = 0; z < n; z++)
if((now & (1<<z)) == 0) //與狀態now互補時
{
int t = now | (1<<z); //now與(1<<z)構成的狀態
for(int d = 0; d <= m; d++)
if(dp[now][d])
{
dp[t][min(d + mp[i][z], m)] += dp[now][d];
}
}
}
top++;
}
if(dp[(1<<n)-1][m] == 0) puts("No solution");
else
{
int gcd = GCD(dp[(1<<n)-1][m], Jie[n]);
printf("%d/%d\n",Jie[n] / gcd, dp[(1 << n) - 1][m] / gcd);
}
}
return 0;
}