UVA1326 Jurassic Remains

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4072

Solution

这题是Meet-in-the-Middle
直接 2n 2 n 枚举的话会超时,因此考虑把整个序列 split s p l i t 成两部分,分别再每一部分中做 2n2 2 n 2 枚举,得到异或和集合 S1 S 1 S2 S 2 ,扫描 S1 S 1 中的每一个元素,在 S2 S 2 中查找有没有相等的元素存在,如果存在就更新答案。
这样做的时间复杂度是 Θ(2n2n) Θ ( 2 n 2 n )
其实所谓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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值