题目链接:https://www.spoj.com/problems/ASSIGN/
参考链接:
1.https://github.com/fazlulkabir94/spoj-problem-solution/blob/master/ASSIGN - Assignments.cpp
2.https://www.quora.com/What-is-__builtin_popcount-in-c++
Problem
Your task will be to calculate number of different assignments of n different topics to n students such that everybody gets exactly one topic he likes.
Input
First line of input contains number of test cases c (1<=c<=80). Each test case begins with number of students n (1<=n<=20). Each of the next n lines contains n integers describing preferences of one student. 1 at the ith position means that this student likes ith topic, 0 means that he definitely doesn’t want to take it.
Output
For each test case output number of different assignments (it will fit in a signed 64-bit integer).
Example
Input:
3
3
1 1 1
1 1 1
1 1 1
11
1 0 0 1 0 0 0 0 0 1 1
1 1 1 1 1 0 1 0 1 0 0
1 0 0 1 0 0 1 1 0 1 0
1 0 1 1 1 0 1 1 0 1 1
0 1 1 1 0 1 0 0 1 1 1
1 1 1 0 0 1 0 0 0 0 0
0 0 0 0 1 0 1 0 0 0 1
1 0 1 1 0 0 0 0 0 0 1
0 0 1 0 1 1 0 0 0 1 1
1 1 1 0 0 0 1 0 1 0 1
1 0 0 0 1 1 1 1 0 0 0
11
0 1 1 1 0 1 0 0 0 1 0
0 0 1 1 1 1 1 1 1 1 1
1 1 0 1 0 0 0 0 0 1 0
0 1 0 1 0 1 0 1 0 1 1
1 0 0 1 0 0 0 0 1 0 1
0 0 1 0 1 1 0 0 0 0 1
1 0 1 0 1 1 1 0 1 1 0
1 0 1 1 0 1 1 0 0 1 0
0 0 1 1 0 1 1 1 1 1 1
0 1 0 0 0 0 0 0 0 1 1
0 1 1 0 0 0 0 0 1 0 1
Output:
6
7588
7426
解释一下这个奇奇怪怪的函数:__builtin_popcount()
用于计算一个 32 位无符号整数有多少个位为1,它并不是c++中的某个头文件中的函数,而是gcc编译器内置的函数,目的在于使用CPU指令加速计算。
AC代码:
# include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
# define ll long long
using namespace std;
int N;
ll dp[(1<<20)+1];
int topic[20][20];
int main()
{
int test;
scanf("%d",&test);
while(test--)
{
scanf("%d",&(N));
for(int i = 0;i < N; i++){
for(int j = 0;j < N; j++){
scanf("%d",&topic[i][j]);
}
}
fill(dp,dp+(1<<N)+1,0);
int maxi = (1<<N);
for(int mask = 0;mask < maxi; mask++)
{
int n = __builtin_popcount(mask);
for(int i = 0;i < N; i++)
if(topic[n][i] == 1 && (mask & (1<<i)) == 0){
if(n == 0)
dp[mask | (1 << i)] = 1;
else
dp[mask | (1 << i)] += dp[mask];
}
}
printf("%lld\n",dp[maxi-1]);
}
return 0;
}