|
楼主的程序如下:
#include <vector>
#include <string>
#include <limits>
#include <iostream>
using namespace std;
struct Point
{
int m_nPoint;
int m_nValue;
string m_szoper;
public:
Point(int nPoint, int nValue, string szoper) : m_nPoint(nPoint), m_nValue(nValue), m_szoper(szoper){}
};
int main(int argc, char* argv[])
{
int nEnd; // 结束值
int nStart; // 起始值
int nCost_Add=6; // +2 价值量 可在=6那输入你+2的价值
int nCost_Del=6; // -2 价值量 可在=6那输入你-2的价值
int nCost_Mul=10; // *2 价值量 可在=10那输入你*2的价值 输入这三个之后就不用再输入三次价值量了
cout << "输入目标值: ";
cin >> nEnd;
cout << "输入起始值: ";
cin >> nStart;
//cout << "+2 价值量: ";
//cin >> nCost_Add;
//cout << "-2 价值量: ";
//cin >> nCost_Del;
//cout << "*2 价值量: ";
//cin >> nCost_Mul;
// 初始状态
vector<Point> vecOperate;
vecOperate.push_back(Point(nStart, 0, ""));
Point sOptimalSolution(nEnd, numeric_limits<int>::max(), ""); // 最优解
while (true)
{
if (vecOperate.size() <= 0)
break;
Point sPoint = vecOperate[0];
vecOperate.erase(vecOperate.begin());
if (sPoint.m_nPoint < nStart ||
sPoint.m_nValue >= sOptimalSolution.m_nValue ||
sPoint.m_szoper.find("+-") != string::npos ||
sPoint.m_szoper.find("-+") != string::npos)
continue;
if (sPoint.m_nPoint == nEnd)
{
sOptimalSolution = sPoint;
continue;
}
vecOperate.push_back( Point(sPoint.m_nPoint + 2, sPoint.m_nValue + nCost_Add, sPoint.m_szoper + string("+")) );
vecOperate.push_back( Point(sPoint.m_nPoint - 2, sPoint.m_nValue + nCost_Del, sPoint.m_szoper + string("-")) );
vecOperate.push_back( Point(sPoint.m_nPoint * 2, sPoint.m_nValue + nCost_Mul, sPoint.m_szoper + string("*")) );
}
cout << "最优消耗:" << sOptimalSolution.m_nValue << endl;
cout << "最优算法:" << sOptimalSolution.m_szoper << endl;
getchar();
getchar();
printf("Hello World!\n");
return 0;
}
//在int nCost_Add 设定初始值,如上面的程序
//可在=6那输入你+2的价值
//可在=6那输入你-2的价值
//可在=10那输入你*2的价值
//输入这三个之后就不用再输入三次价值量了,可省一定的时间。 |
|