Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

水一水,LCA都没必要,就一条查询,直接两个链表走一走就行

Posted by 947186602 at 2020-09-16 11:00:38 on Problem 1330
/**
给你一棵树,
输入 T 样例数 N 节点数 N-1行 from-to 最后一行 x y 的公共祖先
输出 每个样例x y的最近公共祖先
2<=N<=10,000
记录所有点的父亲节点就完事了,因为每个点只有1个父亲
**/
#include<cstdio>
#include<string.h>
using namespace std;
const int MAX_N = 10005;
int par[MAX_N],N,x,y;
bool use_x[MAX_N];
int main(){
     int T;
     scanf("%d",&T);
     while(T--){
          scanf("%d",&N);
          memset(par,-1,sizeof(par));
          memset(use_x,false,sizeof(use_x));
          for(int i = 1;i < N;++i){
               scanf("%d%d",&x,&y);
               par[y] = x;
          }
          scanf("%d%d",&x,&y);
          for(int i = x; ~i; i = par[i]){
               use_x[i] = true;
          }
          for(int i = y; ~i; i = par[i]){
               if(use_x[i]){
                    printf("%d\n",i);
                    break;
               }
          }
     }
     return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator