答案:一个计算24点的c++程序
#include <iostream>
#include <sys/timeb.h>
#include <vector>
#include <string>
#include <stdio.h>using std::vector;
using std::string;
using namespace std;class Node
{
public:
enum OpType
{
UNARY, PLUS, SUB, SUB2, MUL, DIV, DIV2
};double& value(){ return value_; }
double value() const { return value_; }bool Add() { op_ = PLUS; value_ = left_->value_ + right_->value_; return true; }
bool Sub() { op_ = SUB; value_ = left_->value_ - right_->value_; return true; }
bool Sub2() { op_ = SUB2; value_ = right_->value_ - left_->value_; return true; }
bool Mul() { op_ = MUL; value_ = left_->value_ * right_->value_; return true; }
bool Div() { if(right_->value_==0)return false; op_ = DIV; value_ = left_->value_ / right_->value_; return true; }
bool Div2() { if(left_->value_==0)return false; op_ = DIV2; value_ = right_->value_ / left_->value_;return true; }Node( double d = 0 )
: left_(0), right_(0), op_(UNARY), value_(d)
{ }
Node( Node* l, Node *r )
: left_(l), right_(r), op_(UNARY), value_(0)
{ }string getExpr()
{
if( op_ == UNARY )
{
char buf[32];
return "";
}string str;
switch( op_ )
{
case PLUS:
case SUB:
case MUL:
case DIV:
str += "(";
str += left_->getExpr();
str += " +--*//"[op_];
str += right_->getExpr();
str += ")";
break;
case SUB2:
case DIV2:
default:
str += "(";
str += right_->getExpr();
str += " +--*//"[op_];
str += left_->getExpr();
str += ")";
}
return str;
}double value_;
OpType op_;
Node *left_;
Node *right_;
};template<unsigned int L>
bool query( double target, Node** cand, string& expr )
{
for( unsigned int k=0; k<L-1; ++k )
{
Node* newcand[L-1];
for( unsigned int j=k+1; j<L; ++j )
{
for( unsigned int i=k+1; i<j; ++i )
{
if( cand[i]->value() == cand[j]->value() )
continue;
}Node node( cand[k], cand[j] );
Node **pNode = newcand;
for( unsigned int i=0; i<L; ++i )
{
if( i!=k && i!=j )
*pNode++ = cand[i];
}newcand[L-2] = &node;
if( node.Add() && query<L-1>( target, newcand, expr ) )
return true;
if( node.Sub() && query<L-1>( target, newcand, expr ) )
return true;
if( node.Sub2() && query<L-1>( target, newcand, expr ) )
return true;
if( node.Mul() && query<L-1>( target, newcand, expr ) )
return true;
if( node.Div() && query<L-1>( target, newcand, expr ) )
return true;
if( node.Div2() && query<L-1>( target, newcand, expr ) )
return true;
}
}
return false;
}template<>
bool query<1>( double target, Node** cand, string& expr )
{
double diff = target - cand[0]->value();
if( diff < 0.000001 && diff > -0.000001 )
{
//expr = cand[0]->getExpr();
return true;
}
return false;
}int main1( int argc, char** argv)
{
const int LEN = 4;
if( argc != LEN+1 )
{
exit( -1 );
}double target = 24;
Node nodes[LEN];
Node *cands[LEN];
for( int k=0; k<LEN; ++k )
{
int i = atoi( argv[k+1] );
if( i == 0 )
上一个:高手来解决、C++哪里错了
下一个:为什么要说c++是静态语言