Nyoj 43 24 Point game

来源:互联网 发布:淘宝开网店的程序 编辑:程序博客网 时间:2024/05/17 08:47

题目来源:http://acm.nyist.net/JudgeOnline/problem.php?pid=43

有N个元素的数列,若问由这N个元素所组成的表达式,可否等于一个给定的值TargetNum?

分析:如果我们从这N个元素组成的集合中选取两个元素做任意运算符运算,删除集合中这两个选中的元素把计算结果加入到集合中,这样新集合的规模就降为N-1了。类似下去当集合中只剩余一个元素时,看他是否等于TargetNum.

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>using namespace std;const int MAXN = 7;const double Threshold = 1e-6;double a[MAXN];int n;double TargetNum;bool DFS(int pos){    if(pos == n)    {        if(fabs(TargetNum - a[pos]) < Threshold)            return true;        return false;    }    double num1, num2;    for(int i = pos; i < n; ++i)//从n个元素中任意选取两个做任意运算符运算,不一定是最左边那两个    {        for(int j = i+1; j <= n; ++j)        {            num1 = a[i];            num2 = a[j];                        a[i] = a[pos];//注意这个位置很是关键!例如当i = pos+1,j = pos+2时,表示选取的是a[pos+1]和a[pos+2],            //此时a[i] = a[pos+1] = a[pos],把a[i]这个位置的值覆盖掉            //因为a[pos+1]的左边还有元素a[pos],没用上!那么接下来搜索pos = pos+1时候,a[i]就相当于从左边那个没有搜索的元素开始接着搜索            a[j] = num1 + num2;            if(DFS(pos+1))                return true;            a[j] = num1 - num2;            if(DFS(pos+1))                return true;            a[j] = num2 - num1;            if(DFS(pos+1))                return true;            a[j] = num1 * num2;            if(DFS(pos+1))                return true;            if(num1)            {                a[j] = num2/num1;                if(DFS(pos+1))                    return true;            }            if(num2)            {                a[j] = num1/num2;                if(DFS(pos+1))                    return true;            }            a[i] = num1;            a[j] = num2;        }    }    return false;}int main(){    int T;    scanf("%d", &T);    while(T--)    {        scanf("%d %lf", &n, &TargetNum);        for(int i = 1; i <= n; ++i)            scanf("%lf", &a[i]);        if(DFS(1))            printf("Yes\n");        else            printf("No\n");    }    return 0;}


0 0