dfs题目,注意记录状态进行剪枝,否则会超时。
#include <stdio.h>
#include <set>
using namespace std;
#define ADD 0
#define SUB 1
#define MUL 2
#define DIV 3
int arr[120];
char path[120];
bool stop;
int max_index;
int target_value;
long long _hash(int cur, int value)
{
return value*120 + cur;
}
set<long long> hash_map;
void dfs(int oper, int cur, int last_value)
{
if(stop)
return;
if(cur == max_index+1)
{
if(last_value == target_value)
stop = true;
return;
}
int cur_value;
long long hv;
if(last_value<-32000 || last_value>32000)
return;
if(oper==DIV && last_value%arr[cur]!=0)
return;
switch(oper)
{
case ADD:
cur_value = last_value + arr[cur];
path[cur] = '+';
break;
case SUB:
cur_value = last_value - arr[cur];
path[cur] = '-';
break;
case MUL:
cur_value = last_value * arr[cur];
path[cur] = '*';
break;
case DIV:
cur_value = last_value / arr[cur];
path[cur] = '/';
break;
}
hv = _hash(cur, cur_value);
if(hash_map.find(hv) == hash_map.end())
hash_map.insert(hv);
else
return;
dfs(ADD, cur+1, cur_value);
dfs(SUB, cur+1, cur_value);
dfs(MUL, cur+1, cur_value);
dfs(DIV, cur+1, cur_value);
}
void func(int n, int target)
{
int i;
hash_map.clear();
stop = false;
target_value = target;
max_index = n-1;
dfs(ADD, 1, arr[0]);
dfs(SUB, 1, arr[0]);
dfs(MUL, 1, arr[0]);
dfs(DIV, 1, arr[0]);
if(stop)
{
printf("%d", arr[0]);
for(i=1; i<=n-1; i++)
printf("%c%d", path[i], arr[i]);
printf("=%d\n", target);
}
else
{
printf("NO EXPRESSION\n");
}
}
int main(void)
{
int n, m, i;
int target;
//freopen("input.dat", "r", stdin);
scanf("%d", &m);
while(m--)
{
scanf("%d", &n);
for(i=0; i<n; i++)
scanf("%d", arr+i);
scanf("%d", &target);
func(n, target);
}
return 0;
}