跳到正文

个人记录

[TopCoder]SetAndSet

crashed约 5 分钟
原文
文章信息与版本

文章信息

发布
2020年1月31日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

题目

        点这里看题目。

分析

        考虑对二进制位进行容斥。我们每次枚举一个二进制集合SS,表示至少SS中为11的位在红色集合和蓝色集合的ANDAND中是不同的。(其他位如果也有不同的不在考虑范围之内)         考虑计算这样的方案数。按位考虑,当前位为00的数,就必须要放在一起(如果散开和11的混在一起,红集合和蓝集合当前位上就都是00了,不合要求)。所以要用并查集将这一位为00的合在一个集合里,其它为11的每个单独为一个集合。如果此时的集合数量为cntcnt,此时的方案就是2cnt−22^{cnt}-2。         扩展到多个位,SS为11的每一位上都需要把00的全部合到一块,其它的每个单独一个集合。计算答案。         时间是O(n220)O(n2^{20})。

代码

C++
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;

typedef long long LL;

const int MAXN = 55, MAXS = 25;

template<typename _T>
void read( _T &x )
{
	x = 0;char s = getchar();int f = 1;
	while( s > '9' || s < '0' ){if( s == '-' ) f = -1; s = getchar();}
	while( s >= '0' && s <= '9' ){x = ( x << 3 ) + ( x << 1 ) + ( s - '0' ), s = getchar();}
	x *= f;
}

template<typename _T>
void write( _T x )
{
	if( x < 0 ){ putchar( '-' ); x = ( ~ x ) + 1; }
	if( 9 < x ){ write( x / 10 ); }
	putchar( x % 10 + '0' );
}

template<typename _T>
_T MAX( const _T a, const _T b )
{
	return a > b ? a : b;
}

vector<int> bac[MAXS];

int fa[MAXN];
LL ans = 0;
int N;

void makeSet( const int siz ) { for( int i = 1 ; i <= siz ; i ++ ) fa[i] = i; }
int findSet( const int u ) { return fa[u] = ( fa[u] == u ? fa[u] : findSet( fa[u] ) ); }
void unionSet( const int u, const int v ) { fa[findSet( u )] = findSet( v ); }

void DFS( const int indx, const int cnt )
{
	if( indx > 20 )
	{
		int tot = 0;
		for( int i = 1 ; i <= N ; i ++ ) if( fa[i] == i ) tot ++;
		if( cnt & 1 ) ans -= ( 1ll << tot ) - 2;
		else ans += ( 1ll << tot ) - 2;
		return ;
	}
	DFS( indx + 1, cnt );
	if( ! bac[indx].size() ) return ;
	int cur[MAXN], tmp = findSet( bac[indx][0] );
	memcpy( cur, fa, sizeof cur );
	for( int i = 1 ; i < bac[indx].size() ; i ++ ) unionSet( bac[indx][i], tmp );
	DFS( indx + 1, cnt + 1 );
	memcpy( fa, cur, sizeof fa );
}

class SetAndSet
{
	public:
	LL countandset( vector<int> A )
	{
		N = A.size();
		for( int i = 0 ; i < N ; i ++ )
			for( int j = 0 ; j < 20 ; j ++ )
				if( ~ A[i] >> j & 1 ) bac[j + 1].push_back( i + 1 );
		makeSet( N );
		DFS( 1, 0 );
		for( int i = 1 ; i <= 20 ; i ++ ) bac[i].clear();
		return ans;
	}
};
原文