1503 愚蠢的寵物
阿新 • • 發佈:2017-07-21
ont cst define 連接 image isp 表示 output pla
輸入描述 Input Description
1503 愚蠢的寵物
時間限制: 1 s 空間限制: 128000 KB 題目等級 : 黃金 Gold 題目描述 Description
大家都知道,sheep有兩只可愛的寵物(一只叫神牛,一只叫神菜)。有一天,sheep帶著兩只寵物到狗狗家時,這兩只可愛的寵物竟然迷路了……
狗狗的家因為常常遭到貓貓的攻擊,所以不得不把家裏前院的路修得非常復雜。狗狗家前院有N個連通的分叉結點,且只有N-1條路連接這N個節點,節點的編號是1-N(1為根節點)。sheep的寵物非常笨,他們只會向前走,不會退後(只向雙親節點走),sheep想知道他們最早什麽時候會相遇(即步數最少)。
第1行:一個正整數N,表示節點個數。
第2~N行:兩個非負整數A和B,表示A是B的雙親。(保證A,B<=n)
第N+1行:兩個非負整數A和B,表示兩只寵物所在節點的位置。(保證A,B<=n)
輸出描述 Output Description輸出他們最早相遇的節點號。
樣例輸入 Sample Input10
1 2
1 3
1 4
2 5
2 6
3 7
4 8
4 9
4 10
3 6
1
數據範圍及提示 Data Size & Hint對於10%的數據,n<10^6
對於100%的數據,n<=10^6
/* lca能解決的事為什麽要貼上搜索的標簽。。 */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; #define maxn 1000010 int n,s1,s2,head[maxn*2],num,son[maxn],sz[maxn],top[maxn],fa[maxn],dep[maxn]; struct node{ int to,pre; }e[maxn樹剖 lca*2]; void Insert(int from,int to){ e[++num].to=to; e[num].pre=head[from]; head[from]=num; } void dfs1(int u,int father){ sz[u]=1; fa[u]=father; dep[u]=dep[father]+1; for(int i=head[u];i;i=e[i].pre){ int v=e[i].to; if(v==father)continue; dfs1(v,u); sz[u]+=sz[v]; if(!son[u]||sz[v]>sz[son[u]])son[u]=v; } } void dfs2(int u,int father){ top[u]=father; if(son[u])dfs2(son[u],father); else return; for(int i=head[u];i;i=e[i].pre){ int v=e[i].to; if(v==fa[u]||v==son[u])continue; dfs2(v,v); } } int lca(int x,int y){ while(top[x]!=top[y]){ if(dep[top[x]]<dep[top[y]])swap(x,y); x=fa[top[x]]; } if(dep[x]<dep[y])return x; else return y; } int main(){ freopen("Cola.txt","r",stdin); scanf("%d",&n); int x,y; for(int i=1;i<n;i++){ scanf("%d%d",&x,&y); Insert(y,x); Insert(x,y); } scanf("%d%d",&s1,&s2); dfs1(1,0); dfs2(1,1); printf("%d",lca(s1,s2)); }
1503 愚蠢的寵物