//
// main.cpp
// commonAncestor
//
// Created by sj wang on 21/03/2017.
// Copyright © 2017 sj wang. All rights reserved.
//
#include <iostream>
using namespace std;
int tree[]={4,3,1,4,8,2,7,9,2,6,8,7,1,8,2,5};
int len=16;
int *book1 =new int[len];
int *book2 =new int[len];
int t1=0;
int t2=0;
int counts=0;
void getformat(char *tmp)
{
int len = strlen(tmp);
}
int readAndShow(){
FILE *fp;
fp = fopen("/Users/sjwang/Desktop/forTest1/2" , "r");
fseek( fp , 0 , SEEK_END );
int file_size;
file_size = ftell( fp );
// printf( "%d" , file_size );
// char *tmp;
// tmp = (char *)malloc( (file_size+1) * sizeof( char ) );
char tmp[10000];
fseek( fp , 0 , SEEK_SET);
fread( tmp , file_size , sizeof(char) , fp);
tmp[file_size] = '\0';
fclose(fp);
printf("%s" , tmp );
return 0;
}
void swapTwo(int a, int b){
int tmp=0;
tmp=tree[b];
tree[b]=tree[a];
tree[a]=tmp;
return;
}
void preSort(){
int min;
for(int i=0; i<len-1; i=i+2){
// cout<<"i= "<<i<<endl;
min=i;
for(int j=i; j<len-1; j=j+2){
// cout<<"j= "<<j<<endl;
if(tree[j+2]<=tree[min]){
min=j+2;
}
//cout<<"min= "<<min<<endl;
//cout<<""<<endl;
}
swapTwo(i, min);
swapTwo(i+1,min+1);
//cout<<"swap "<<i<<endl;
//cout<<"swap:"<<i<<""<<i+1<<endl;
}
}
// return the index of father
int findFather(int num){
for(int i=0; i<len; i++){
if(tree[i]==num && i%2==1){
return i-1;
}
}
return -1;
}
// return index
int findFirstChild(int num){
for(int i=0; i<len; i++){
if(tree[i]==num && i%2==0){
return i+1;
}
}
return -1;
}
// return index
int findSecondChild(int num){
int q=0;
for(int i=0; i<len; i++){
if(tree[i]==num && i%2==0){
q++;
}
if(q==2){
return i+1;
}
}
return -1;
}
void AncestorsOf1(int num){
if(findFather(num)!=-1){
book1[t1]=tree[findFather(num)];
t1++;
AncestorsOf1(tree[findFather(num)]);
}
}
void AncestorsOf2(int num){
if(findFather(num)!=-1){
book2[t2]=tree[findFather(num)];
t2++;
AncestorsOf2(tree[findFather(num)]);
}
}
int commonAnces(int num1, int num2){
AncestorsOf1(num1);
AncestorsOf2(num2);
for(int i=0; i<len; i++){
for(int j=0; j<len; j++){
if(book1[i]==book2[j]){
return book1[i];
}
}
}
return -1;
}
void countNum(int num){
if(findFather(num!=-1)){
if(findFirstChild(num)!=-1){
counts++;
countNum(tree[findFirstChild(num)]);
}
if(findSecondChild(num)!=-1){
counts++;
countNum(tree[findSecondChild(num)]);
}
}
}
int main() {
// insert code here...
for(int i=0; i<len; i++){
book1[i]=0;
}
for(int i=0; i<16; i++){
cout<<tree[i]<<" ";
}
cout<<""<<endl;
for(int i=0; i<16; i++){
cout<<tree[i]<<" ";
}
countNum(8);
cout<<"Number is = "<<counts<<endl;
//cout<<"Common ancestor: "<<commonAnces(6, 3)<<endl;
//readAndShow();
cout << "Hello, World!\n";
return 0;
}
随意写的
最新推荐文章于 2023-06-27 12:21:56 发布