# 用C++求最长递增子序列

#include <deque>
#include <cassert>
void MaxIncreaseQueue(const std::deque<int> & source,std::deque<int> & result)
{
typedef std::deque<int> IntArray;
//怎样从source中得到最长递增子序列放到result中？
}

class GetMinValue
{
int minvalue_;
public:
explicit GetMinValue(const IntArray & in){
assert(in.size() != 0);
IntArray::const_iterator i = in.begin();
for(minvalue_ = *i,++i;i != in.end();++i){
if(minvalue_ > *i)
minvalue_ = *i;
}
}
~GetMinValue(){}
operator int() const{
return minvalue_;
}
};

int min = GetMinValue(source);

2   ——父节点值比子节点小
/ /
6   3 ——右节点值比左节点小

class Node
{
int value_,length_;
Node *parent_,*rightchild_,*leftbrother_;
public:
Node(Node * parent,int value):value_(value),length_(1),parent_(parent),rightchild_(0),leftbrother_(0){
if(parent_ != 0){
length_ = parent->length_ + 1;
leftbrother_ = parent->rightchild_;
parent->rightchild_ = this;
}
}
~Node(){
if(rightchild_)
delete rightchild_;
if(leftbrother_)
delete leftbrother_;
}
//Functions for member access
int Value() const{
return value_;
}
int Length() const{
return length_;
}
Node * Parent() const{
return parent_;
}
Node * RightChild() const{
return rightchild_;
}
Node * LeftBrother() const{
return leftbrother_;
}
};

rightchild_等定义为public，或提供一个修改的接口。

class Tree
{
Node root_,*max_length_node_;
}
if(!parent || val < parent->Value())
return false;
int count = 0;
for(Node * p = parent->RightChild();p != 0;p = p->LeftBrother(),++count){
break;
}
if(!count)
AppendNode(parent,val);
return true;
}
void AppendNode(Node * parent,int val){
Node * p = new Node(parent,val);
if(p->Length() > max_length_node_->Length()){
max_length_node_ = p;
}
}
public:
explicit Tree(int value):root_(0,value),max_length_node_(&root_){}
~Tree(){}
void InputIntArray(const IntArray & in){
for(IntArray::const_iterator i = in.begin();i != in.end();++i){
}
}
void OutputIntArray(IntArray & out){
out.erase(out.begin(),out.end());
Node * p = max_length_node_;
while(p != &root_){
out.push_front(p->Value());
p = p->Parent();
}
}
};

Tree的构造函数主要用来初始化root_，要使得root_.value_的值是最小的，理由我已经说过了。析构函数更是简单得没有明显的代码。

void MaxIncreaseQueue(const std::deque<int> & source,std::deque<int> & result)
{
Tree t = Tree(GetMinValue(source));
t.InputIntArray(source);
t.OutputIntArray(result);
}

int main()
{
typedef deque<int> IntArray;
const int size = 30;
int array[size] = {5,4,9,4,6,1,7,4,3,5,7,5,3,2,3,4,5,8,1,6,5,4,0,0,1,0,0,0,0,0};
IntArray source(array,array + size),result;
MaxIncreaseQueue(source,result);
cout<<"Max Queue:";
for(IntArray::const_iterator i = result.begin();i != result.end();++i)
cout<<*i<<' ';
cout<<'/n';
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120