[TopCoder]SetAndSet
题目
点这里看题目。
分析
考虑对二进制位进行容斥。我们每次枚举一个二进制集合
考虑计算这样的方案数。按位考虑,当前位为
扩展到多个位,
时间是
代码
#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;
}
};