哈希 A+B Problem

本文介绍了一个解决由'0','1','?'组成的字符串序列的A+B=C问题的算法,涉及长度不超过10的字符串匹配与计算。

A+B Problem

Case Time Limit: 1000ms
Memory Limit: 65536KB

Description

给定三个由'0','1','?'构成的字符串s0,s1,s2,其中'?'表示该位可能是0也可能是1。如果有三个数A,B,C满足这三个数的二进制依 次是这三个字符串,且有A+B=C则称有序三元组<A,B,C>是这三个字符串的一组解。例如<0,2,2>和< 1,2,3>都是{"0?","10","1?"}的解。现在给定s0,s1,s2,求解的个数。

Input

输入为三个由'0','1','?'构成的字符串s0,s1,s2,任意一个字符串的长度都不超过10。

Output

输出整数表示解的个数。

Sample Input

0?
10
1?
之前做过poj上类似的题,不过这题实现起来要麻烦点
View Code
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

char a[20],b[20],c[20];
int tab1[20];
int tab2[20];
int tab3[20];
int tab[2050];

int main()
{
while(cin>>a>>b>>c)
{
int len1=strlen(a),top1=0;
int len2=strlen(b),top2=0;
int a1=0,b1=0,c1=0;
for(int i=len1-1;i>=0;i--)
if(a[i]=='?') tab1[top1++]=1<<(len1-i-1);
else if(a[i]=='1') a1+=1<<(len1-i-1);
for(int i=len2-1;i>=0;i--)
if(b[i]=='?') tab2[top2++]=1<<(len2-i-1);
else if(b[i]=='1') b1+=1<<(len2-i-1);
// cout<<a1<<" "<<b1<<endl;
// cout<<top1<<" "<<top2<<endl;
memset(tab,0,sizeof(tab));
int top=max(top1,top2);
for(int i=0;i<=(1<<top1)-1;i++)
for(int j=0;j<=(1<<top2)-1;j++)
{
int op1=0,op2=0;
for(int k=0;k<top;k++)
{
if(i&(1<<k)) op1+=tab1[k];
if(j&(1<<k)) op2+=tab2[k];
}
tab[op1+op2+a1+b1]++;
// cout<<op1<<" "<<op2<<endl;
}
int len3=strlen(c),top3=0;
for(int i=len3-1;i>=0;i--)
if(c[i]=='?') tab3[top3++]=1<<(len3-1-i);
else if(c[i]=='1') c1+=1<<(len3-1-i);
int ans=0;
for(int i=0;i<(1<<top3);i++)
{
int op3=0;
for(int k=0;k<top3;k++)
if(i&(1<<k)) op3+=tab3[k];
ans+=tab[c1+op3];
// cout<<op3<<" "<<tab[c1+op3]<<endl;
}
printf("%d\n",ans);
}
return 0;
}

转载于:https://www.cnblogs.com/one--world--one--dream/archive/2012/04/01/2429006.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值