HDU 4403 A very hard Aoshu problem (暴力+状态压缩)


Problem Description
Aoshu is very popular among primary school students. It is mathematics, but much harder than ordinary mathematics for primary school students. Teacher Liu is an Aoshu teacher. He just comes out with a problem to test his students:

Given a serial of digits, you must put a '=' and none or some '+' between these digits and make an equation. Please find out how many equations you can get. For example, if the digits serial is "1212", you can get 2 equations, they are "12=12" and "1+2=1+2". Please note that the digits only include 1 to 9, and every '+' must have a digit on its left side and right side. For example, "+12=12", and "1++1=2" are illegal. Please note that "1+11=12" and "11+1=12" are different equations.
 

Input
There are several test cases. Each test case is a digit serial in a line. The length of a serial is at least 2 and no more than 15. The input ends with a line of "END".
 

Output
For each test case , output a integer in a line, indicating the number of equations you can get.
 

Sample Input
   
   
   
   
1212 12345666 1235 END
 

Sample Output
   
   
   
   
2 2 0
 

Source
2012 ACM/ICPC Asia Regional Jinhua Online


将每种加法的位置,状态压缩一下,1表示加好,0表示连接在一起


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int num[22],n;
char s[22];

bool dfs(int s1,int s2,int cnt)
{
	int tem,a,b,i,q;
	tem=num[1];
	a=0;
	for(i=1;i<cnt;i++) {
		if(s1&(1<<(i-1))) {
			a+=tem;
			tem=num[i+1];
		}
		else tem=tem*10+num[i+1];
	}
	a+=tem;
	tem=num[cnt+1];
	b=0;
	for(i=cnt+1;i<n;i++) {
		q=i-cnt-1;
		if(s2&(1<<q)) {
			b+=tem;
			tem=num[i+1];
		}
		else tem=tem*10+num[i+1];
	}
	b+=tem;
	if(b==a) return true;
	return false;
}




int main()
{
	int i,j,s1,s2,ans;
	while(scanf("%s",s)!=EOF) {
		ans=0;
		if(strcmp(s,"END")==0) break;
		n=strlen(s);
		for(i=0;i<n;i++) num[i+1]=s[i]-'0';
		for(i=1;i<n;i++) {
			int t1=(1<<(i-1));    //状态压缩,枚举每种加号的位置 
			int t2=(1<<(n-i-1));
			 for(s1=0;s1<t1;s1++) {
			 	for(s2=0;s2<t2;s2++) {
			 		if(dfs(s1,s2,i)) ans++;
				 }
			 }
		}
		printf("%d\n",ans);
	}
	return 0;
}






你可能感兴趣的:(HDU 4403 A very hard Aoshu problem (暴力+状态压缩))