-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path最近公共祖先
147 lines (146 loc) · 3.2 KB
/
最近公共祖先
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 200
#define M 200
struct Node
{
char a[N];
int numChild;
struct Node *father;
struct Node *child[N];
};
struct Node* searchFather(struct Node *ancient,char father[])
{
int i;
int num=ancient->numChild;
struct Node *p;
if(0==strcmp(ancient->a,father))
{
return ancient;
}
else
{
for(i=0;i<num;i++)
{
p=searchFather(ancient->child[i],father);
if(p!=NULL)
return p;
}
}
return NULL;
}
int insertNode(struct Node *ancient[],int* numAncient,char father[],char child[])
{
struct Node *p=NULL,*temp;
int i;
for(i=0;i<*numAncient;i++)
{
p=searchFather(ancient[i],father);
if(p!=NULL)
break;
}
temp=(struct Node*)malloc(sizeof(struct Node));
if(NULL==temp)
{
perror("failed");
exit(-1);
}
memset(temp,0,sizeof(struct Node));
if(NULL==p)//如果父节点不存在则先插入父节点
{
ancient[(*numAncient)++]=temp;
strcpy(temp->a,father);
return 0;
}
else
{
p->child[p->numChild++]=temp;
temp->father=p;
strcpy(temp->a,child);
}
return 1;
}
void searchSameAncient(struct Node *ancient[],int numAncient,char father[],char child[])
{
struct Node *pf,*pc;
char a[M][N],b[M][N];
int i,ia,ib,flag;
ia=ib=flag=0;
pf=pc=NULL;
for(i=0;i<numAncient;i++)
{
pf=searchFather(ancient[i],father);
if(pf!=NULL)
break;
}
if(pf!=NULL)
{
strcpy(a[ia++],pf->a);
while(pf->father!=NULL)
{
pf=pf->father;
strcpy(a[ia++],pf->a);
}
}
for(i=0;i<numAncient;i++)
{
pc=searchFather(ancient[i],child);
if(pc!=NULL)
break;
}
if(pc!=NULL)
{
strcpy(b[ib++],pc->a);
while(pc->father!=NULL)
{
pc=pc->father;
strcpy(b[ib++],pc->a);
}
}
ia--;
ib--;
while(ia>=0 && ib>=0 && 0==strcmp(a[ia],b[ib]))
{
ia--;
ib--;
flag=1;
}
if(NULL==pf || NULL==pc)
{
printf("-1\n");
return;
}
else if(flag)
printf("%s\n",a[ia+1]);
else
printf("-1\n");
}
int main()
{
int i,n,numAncient;
char father[N],child[N];
struct Node *ancient[M],*p;
memset(ancient,0,sizeof(ancient));
numAncient=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s %s",father,child);
if(0==insertNode(ancient,&numAncient,father,child))
{
insertNode(ancient,&numAncient,father,child);
}
}
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s %s",father,child);
if(0==strcmp(father,child))
printf("%s",father);
else
searchSameAncient(ancient,numAncient,father,child);
}
system("pause");
return 0;
}