您的位置:首页 > 其它

算法(求对输入的N个数进行加法或减法运算,得到最小的正整数的组合.)

2005-12-11 13:01 417 查看
/**
*
* 对输入的N个数进行加法或减法运算,得到最小的正整数的组合,并将运算
* 序列打印出来。
*
* 算法思想:二叉树搜索比较
*
*
*@Author:ChengZengcun
*@Date :2005/12/10
*
**/
#include <iostream>
using namespace std;
#define N 5
int data
={0};
int status
={1}; //存储最终数据的正负
int old_s
={1};
int sum=0;
void getMin(int index,bool isPositive)
{
if(index==N){
int t=0;
for(int i=0; i<N; i++){
t+=(int)old_s[i]*data[i]; //operate the current value
}
if(t<sum && t>=0 ){
//Find the less num
for(int i=0; i<N; i++){
status[i]=old_s[i];//Store the newest status
///for test
cout<<"****"<<status[i];
}
cout<<"*****"<<endl;
sum = t;
}
return; //递归的出口
}

if(isPositive){
old_s[index]=1;
}else{
old_s[index]=-1;
}

getMin(index+1,true);
getMin(index+1,false); //二叉树搜索
}
int main()
{
cout<<"Please input "<<N<<" numbers"<<endl;
int i=0;
int a=0;
while(i<N){
cin>>a;
data[i]=a;
sum+=a;
i++;
}
cout<<"Start to manage the operation"<<endl;

getMin(0,true);
getMin(0,false);

i=0;
cout<<"the result getted:"<<endl;
while(i<N){
if(status[i]>0){
cout<<"+";
}else{
cout<<"-";
}
cout<<data[i];
i++;
}
cout<<" = "<<sum<<endl;

system("PAUSE");
return 0;
}
以上是我自己写的程序,没有仔细考虑程序分配以及时间复杂度等因素.只是简单的实现,希望可以交流.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐