pipioj 1265: 最近公共祖先

http://www.pipioj.online/problem.php?id=1265

 1 #define bug(x) cout<<#x<<" is "<<x<<endl
 2 #define IO std::ios::sync_with_stdio(0)
 3 #define ull unsigned long long
 4 #include <bits/stdc++.h>
 5 #define iter ::iterator
 6 #define pa pair<int,ll>
 7 #define pp pair<int,pa>
 8 using namespace  std;
 9 #define ll long long
10 #define mk make_pair
11 #define pb push_back
12 #define se second
13 #define fi first
14 #define ls o<<1
15 #define rs o<<1|1
16 ll mod=998244353;
17 const int N=2e5+5;
18 
19 vector<int>g[N];
20 
21 int a[N],b[N],c[N];
22 int l[N],r[N],fa[N];
23 
24 int tot=1,cnt=0;
25 
26 void dfs(int x){
27     if(tot>cnt)return;
28     if(x==-1){
29         return;
30     }
31     
32     l[x]=a[++tot];
33     fa[a[tot]]=x;
34     dfs(a[tot]);
35     r[x]=a[++tot];
36     fa[a[tot]]=x;
37     dfs(a[tot]);
38 }
39 
40 void dfs1(int x){
41     printf("%d\n",x);
42     if(l[x])dfs1(l[x]);
43     else if(r[x])dfs1(r[x]);
44 
45 }
46 int main(){
47     IO;
48     int x;
49     while(cin>>x){
50         a[++cnt]=x;
51     }
52     fa[a[1]]=-1;
53     dfs(a[1]);
54     int y,n1=0,n2=0;
55     y=a[cnt-1];
56     while(y!=-1){
57         b[++n1]=y;
58         y=fa[y];
59     }
60     y=a[cnt];
61     while(y!=-1){
62         c[++n2]=y;
63         y=fa[y];
64     }
65     if(n1>n2){
66         for(int i=1;i<=n2;i++){
67             if(b[i+n1-n2]==c[i]){
68                 cout<<c[i]<<endl;
69                 break;
70             }
71         }
72     }
73     else{
74         for(int i=1;i<=n1;i++){
75             if(b[i]==c[i+n2-n1]){
76                 cout<<b[i]<<endl;
77                 break;
78             }
79         }
80     }
81     /*for(int i=1;i<=8;i++){
82         printf("i=%d: %d  %d\n",i,l[i],r[i]);
83     }*/
84     
85 
86 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章