Spoj ASSIGN - Assignments dp+bitmasking

题目链接: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值