您的位置:首页 > 其它

5-31笛卡尔树(25 分)

2016-04-24 16:03 393 查看



#include <iostream>
#include "queue"
#include "deque"
#include "algorithm"
#include "string.h"
using namespace std;

#define Max 100
struct Le
{
int k1,k2;
int left,right;
};
Le A[Max];
int Examine[Max];
struct Node
{
int K1;
int K2;
Node *Left;
Node *Right;
};
deque<int>Q1,Q2;
class Tree
{
private:
Node *root;
public:
Tree(){root=NULL;}
Node*& Root(){return root;}
void Output(Node *p);
void Output();
void JudgeK1(Node *p);
void JudgeK1();
bool JudgeK2(Node *p);
bool JudgeK2();
};
bool Tree::JudgeK2()
{
return JudgeK2(root);
}
bool Tree::JudgeK2(Node *p)
{
if(p==NULL) return true;
if(p->Left==NULL && p->Right==NULL) return true;
if(p->Left!=NULL && p->Right==NULL)
{
if(p->K2<p->Left->K2) return true;
return false;
}
if(p->Left==NULL && p->Right!=NULL)
{
if(p->K2<p->Right->K2) return true;
return false;
}
bool T1,T2;
T1=JudgeK2(p->Left);
T2=JudgeK2(p->Right);

if(T1 && T2) return true;
return false;

}
void Tree::JudgeK1()
{
JudgeK1(root);
}
void Tree::JudgeK1(Node *p)
{
if(p!=NULL)
{
JudgeK1(p->Left);
Q1.push_back(p->K1);
Q2.push_back(p->K1);
JudgeK1(p->Right);
}
}
void Build(Node *&p,int i)
{
p=new Node;
p->K1=A[i].k1;
p->K2=A[i].k2;
if(A[i].left!=-1)
{
Build(p->Left,A[i].left);
}
else p->Left=NULL;
if(A[i].right!=-1)
{
Build(p->Right,A[i].right);
}
else p->Right=NULL;
}

int main()
{

memset(Examine,0,sizeof(Examine));
int n,i;
cin>>n;
for(i=0;i<n;i++)
{
cin>>A[i].k1>>A[i].k2>>A[i].left>>A[i].right;
if(A[i].left!=-1) Examine[A[i].left]=1;
if(A[i].right!=-1) Examine[A[i].right]=1;
}
int root=0;
while(Examine[root]==1)
root++;
Tree tree;
Build(tree.Root(),root);
bool flag=true;

tree.JudgeK1();

sort(Q2.begin(),Q2.end());

for(i=0;i<Q1.size();i++)
{
if(Q1[i]>Q2[i])
flag=false;
}
if(flag==false)
{
cout<<"NO"<<endl;
}
else
{
if(tree.JudgeK2())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: