HDOJ(HDU).2266 How Many Equations Can You Find (DFS)
HDOJ(HDU).2266 How Many Equations Can You Find (DFS) [从零开始DFS(9)]
从零开始DFS
HDOJ.1342 Lotto [从零开始DFS(0)] — DFS思想与框架/双重DFS
HDOJ.1010 Tempter of the Bone [从零开始DFS(1)] —DFS四向搜索/奇偶剪枝
HDOJ(HDU).1015 Safecracker [从零开始DFS(2)] —DFS四向搜索变种
HDOJ(HDU).1016 Prime Ring Problem (DFS) [从零开始DFS(3)] —小结:做DFS题目的关注点
HDOJ(HDU).1035 Robot Motion [从零开始DFS(4)]—DFS题目练习
HDOJ(HDU).1241 Oil Deposits(DFS) [从零开始DFS(5)] —DFS八向搜索/双重for循环遍历
HDOJ(HDU).1258 Sum It Up (DFS) [从零开始DFS(6)] —DFS双重搜索/去重技巧
HDOJ(HDU).1045 Fire Net [从零开始DFS(7)]—DFS练习/check函数的思想
POJ.1416 Shredding Company [从零开始DFS(8)]—DFS练习/sum函数的设计
HDOJ(HDU).2266 How Many Equations Can You Find (DFS) [从零开始DFS(9)]—DFS练习
题意分析
和POJ.1416 Shredding Company [从零开始DFS(8)]一模一样,简直了!
唯一需要注意的就是有可能不是求和,而是做减法。于是又多了一层dfs。当gap[i] = 2的时候代表做减法。求和的时候相减就行了。上代码上代码,快哉!
代码总览
/*
Title:HDOJ.2266
Author:pengwill
Date:2017-2-14
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char nu[100];
int num[100],gap[100],save[100];
int ret,len,test,time= 0;
long long tar;
void init()
{
memset(gap,0,sizeof(gap));
len = strlen(nu);
for(int i = 0,j = 1; i<len;++i,++j) num[j] = nu[i]-'0';
ret = 0;gap[0] = gap[len] = 1; test = 0;time = 0;
}
int sum()
{
int base = 1; int ans = 0; int t = 0;
for(int i = len ; i>=0; --i){
if(gap[i] == 0){
base*=10;
t += num[i] * base;
}else if(gap[i] == 1){
ans+=t; base = 1;
t = num[i] * base;
}else if(gap[i] == 2){
ans-=t; base = 1;
t = num[i] * base;
}
}
return ans;
}
void cpy()
{
for(int i = 0; i<=len ;++i) save[i] = gap[i];
}
void output()
{
for(int i = 1;i<=len;++i){
printf("%d",num[i]);
if(i!=len){
if(save[i] == 1) printf(" ");
}
}
printf("\n");
}
void dfs(int depth,int tag)
{
if(len==depth){
int t = sum();
if(t == tar) ret++;
return;
}
gap[depth] = tag;
if(depth == len-1){
dfs(depth+1,1);//chose gap
}else{
dfs(depth+1,1);//chose gap +
dfs(depth+1,0);//don't chose gap
dfs(depth+1,2);//chose gap -
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%s %lld",&nu,&tar)!= EOF){
init();
dfs(0,1);
printf("%d\n",ret);
}
return 0;
}