Link
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4072
Solution
这题是Meet-in-the-Middle
直接
枚举的话会超时,因此考虑把整个序列
成两部分,分别再每一部分中做
枚举,得到异或和集合
和
,扫描
中的每一个元素,在
中查找有没有相等的元素存在,如果存在就更新答案。
这样做的时间复杂度是
其实所谓Meet-in-the-Middle也是一种分治思想,只不过一般的分治是递归分治下去,而这个是把整体问题划分成两部分,每一部分分别暴力,然后合并。
Code
//Meet-in-the-Middle
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#include <string>
#define ll long long
#define cl(x) memset(x,0,sizeof(x))
#define maxn 24
using namespace std;
ll N, n[maxn+10], now, status, ans, Sta;
map<ll,ll> table;
ll bitcount(ll x)
{
ll cnt=0;
for(;x;x>>=1)cnt+=x&1;
return cnt;
}
void dfs1(ll dep)
{
if(dep>(N>>1))
{
map<ll,ll>::iterator it=table.find(now);
if(it==table.end())table[now]=status;
else if(bitcount(it->second)<bitcount(status))it->second=status;
return;
}
now^=n[dep];
status^=1ll<<dep-1;
dfs1(dep+1);
now^=n[dep];
status^=1ll<<dep-1;
dfs1(dep+1);
}
void dfs2(ll dep)
{
if(dep>N)
{
map<ll,ll>::iterator it=table.find(now);
if(it!=table.end())
{
ll t=bitcount(it->second)+bitcount(status);
if(t>ans)
{
ans=t;
Sta=it->second^status;
}
}
return;
}
now^=n[dep];
status^=1ll<<dep-1;
dfs2(dep+1);
now^=n[dep];
status^=1ll<<dep-1;
dfs2(dep+1);
}
void display()
{
ll i;
printf("%lld\n",ans);
for(i=0;i<N;i++)if(Sta&(1ll<<i))printf("%lld ",i+1);
printf("\n");
}
void init()
{
ll i, x, j;
char s[1000];
for(i=1;i<=N;i++)
{
scanf("%s",s);
for(j=0;s[j];j++)n[i]^=1ll<<s[j]-'A';
}
}
int main()
{
while(~scanf("%lld",&N))
{
ans=0;
Sta=0;
table.clear();
cl(n);
init();
dfs1(1);
dfs2((N>>1)+1);
display();
}
return 0;
}