SlideShare une entreprise Scribd logo
1  sur  14
Lowest Common Ancestor


Md. Shakil Ahmed
Software Engineer
Astha it research & consultancy ltd.
Dhaka, Bangladesh
lowest common ancestor (LCA)
• The lowest common ancestor (LCA) is a
  concept in graph theory and computer
  science. Let T be a rooted tree with n nodes.
  The lowest common ancestor is defined
  between two nodes v and w as the lowest
  node in T that has both v and w as
  descendants (where we allow a node to be a
  descendant of itself).
lowest common ancestor (LCA)
LightOJ: 1101 - A Secret Mission
There will be N evil cities (numbered by 1, 2, ..., N) connected
  by M bidirectional roads. There will be evil guards
  patrolling the roads. Since they are not much intelligent,
  the danger of travelling in each road is not the same. Alice
  is going to travel from city s to city t. You can safely assume
  that it's possible to travel from any city to another. John
  the legend programmer has estimated the danger of each
  road but since he is busy arranging contests, Alice is
  depending on you now. Danger of a path from city s to city
  t is defined as the maximum danger of any road on this
  path. As you are one of the most talented programmers,
  you will love to help Alice by finding the least dangerous
  paths to prevent Evil Jack from doing harms to the Judges.
LightOJ: 1101 - A Secret Mission
Input
Input starts with an integer T (≤ 3), denoting the number of
   test cases.
Each case contains two integers N, M (2 ≤ N ≤ 50000, 1 ≤ M ≤
   105) denoting the number of cities and roads. Each of the
   next M lines contains three integers: xi, yi, di (1 ≤ xi, yi ≤ N, xi
   ≠ yi, 1 ≤ di ≤ 104) - the cities connected by the ith road and its
   degree of danger. Next line contains an integer q (1 ≤ q ≤
   50000). Each of the next q lines contains two integers: si
   and ti (1 ≤ si, ti ≤ N, si ≠ ti).
Output
For each test case, print the case number first. Then for each
   query si ti, print the least dangerous path in a line.
LightOJ: 1101 - A Secret Mission
LightOJ: 1101 - A Secret Mission
                      int cmp( const void *a, const void
#include<stdio.h>
                      *b )
#include <stdlib.h>   {
struct T                T *p = (T *)a;
{                       T *q = (T *)b;
   int x;
                          return ( p->weight - q->weight );
   int y;             }
   int weight;
};                    int cmp1( const void *a, const void
                      *b )
                      {
struct TT
                        TT *p = (TT *)a;
{                       TT *q = (TT *)b;
   int x;
   int y;                 return ( p->x - q->x );
   int weight;        }
};
LightOJ: 1101 - A Secret Mission
                                     void dfs(int h1,int h2,int h3,int h4)
T a[100009];                         {
TT A[100009];                        PP[h1][0]=h2;
                                     MX[h1][0]=h3;
int P[50009],ind[50009],N;
                                     L[h1]=h4;
int Parent(long h1)
{                                    int h5;
if(P[h1]==-1)
return h1;                           for(h5=ind[h1];h5<N;h5++)
                                     {
P[h1]=Parent(P[h1]);
                                     if(A[h5].x!=h1)
return P[h1];                        break;
}                                    if(A[h5].y!=h2)
int PP[50009][20], MX[50009][20],    dfs(A[h5].y,h1,A[h5].weight,h4+1);
     L[50009];
int cas,cas1,n,m,i,h1,h2,j,flag,q;   }
int q1,x,y,z,max;                    }
LightOJ: 1101 - A Secret Mission
int main()                                        for(i=0;i<m;i++)
{                                                 {
                                                  h1 = Parent(a[i].x);
scanf("%d",&cas);                                 h2 = Parent(a[i].y);
                                                  if(h1!=h2)
for(cas1=1;cas1<=cas;cas1++)
{                                                 {
scanf("%d %d",&n,&m);                             P[h1]=h2;
                                                  A[N].x = a[i].x;
for(i=0;i<m;i++)                                  A[N].y = a[i].y;
scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].weight);
                                                  A[N].weight = a[i].weight;
qsort(a,m,sizeof(T),cmp);                         N++;
                                                  A[N].x = a[i].y;
for(i=1;i<=n;i++)                                 A[N].y = a[i].x;
P[i]=-1;                                          A[N].weight = a[i].weight;
N = 0;                                            N++;
                                                  }
                                                  }
LightOJ: 1101 - A Secret Mission

qsort(A,N,sizeof(TT),cmp1);   for(i=1;i<=n;i++)
                              {
for(i=1;i<=n;i++)               if(PP[i][j-1]!=-1 && PP[PP[i][j-1]][j-1]!=-1)
{                               {
ind[i]=-1;                        PP[i][j]= PP[PP[i][j-1]][j-1];
}                                 MX[i][j]=MX[i][j-1];
                                  if(MX[i][j]<MX[PP[i][j-1]][j-1])
for(i=0;i<N;i++)
                                  MX[i][j]=MX[PP[i][j-1]][j-1];
if(ind[A[i].x]==-1)               flag = 1;
ind[A[i].x] = i;                }
                                else
dfs(1,-1,-1,0);                 PP[i][j]=-1;
                              }
for(j=1;;j++)
{                             if(flag==0)
flag = 0;                     break;
                              }
LightOJ: 1101 - A Secret Mission
scanf("%d",&q);              while(L[x]!=L[y])
printf("Case %d:n",cas1);   {

for(q1=1;q1<=q;q1++)         for(i=0;;i++)
{                            {
scanf("%d %d",&x,&y);        if(PP[y][i]==-1||L[PP[y][i]]<L[x])
max = 0;                     {
                             y = PP[y][i-1];
if(L[x]>L[y])                break;
{                            }
z = x;                       else if(MX[y][i]>max)
x = y;                       max = MX[y][i];
y = z;                       }
}
                             }
LightOJ: 1101 - A Secret Mission
while(x!=y)               else
{                         {
for(i=0;i<20;i++)           x = PP[x][i-1];
                            y = PP[y][i-1];
{                         }
if(PP[x][i]==PP[y][i])    break;
{                        }
  if(i==0)               else
                         {
  {
                         if(MX[x][i]>max)
     if(MX[x][i]>max)    max = MX[x][i];
     max = MX[x][i];     if(MX[y][i]>max)
     if(MX[y][i]>max)    max = MX[y][i];
     max = MX[y][i];     }} }
                         printf("%dn",max);
     x = PP[x][i];
                         } }
     y = PP[y][i];       return 0;
  }                      }
Sample
• LightOJ:
  http://www.lightoj.com/volume_problemcate
  gory.php?user_id=3060&category=Range
  %20Minimum%20Query/Lowest%20Common
  %20Ancestor
Thanks!

Contenu connexe

Tendances

5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programmingKrish_ver2
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonshin
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingPrudhviVuda
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and PolynomialAroosa Rajput
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexityashishtinku
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsHarry Potter
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithmspppepito86
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsChris Eargle
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysisDr. Rajdeep Chatterjee
 

Tendances (16)

5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and Polynomial
 
Arrays
ArraysArrays
Arrays
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 
Lec16
Lec16Lec16
Lec16
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
Lec4
Lec4Lec4
Lec4
 

Similaire à Lowest common ancestor

Matlab assignment
Matlab assignmentMatlab assignment
Matlab assignmentRutvik
 
Computer Graphics Lab File C Programs
Computer Graphics Lab File C ProgramsComputer Graphics Lab File C Programs
Computer Graphics Lab File C ProgramsKandarp Tiwari
 
10CSL67 CG LAB PROGRAM 9
10CSL67 CG LAB PROGRAM 910CSL67 CG LAB PROGRAM 9
10CSL67 CG LAB PROGRAM 9Vanishree Arun
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingShakil Ahmed
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignmentashikul akash
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfapexelectronices01
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligenceAditya Sharma
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C ProgramsKandarp Tiwari
 
Query Suggestion @ tokyotextmining#2
Query Suggestion @ tokyotextmining#2Query Suggestion @ tokyotextmining#2
Query Suggestion @ tokyotextmining#2ybenjo
 
Graph for Coulomb damped oscillation
Graph for Coulomb damped oscillationGraph for Coulomb damped oscillation
Graph for Coulomb damped oscillationphanhung20
 
Advanced Search Techniques
Advanced Search TechniquesAdvanced Search Techniques
Advanced Search TechniquesShakil Ahmed
 
Stat150 spring06 markov_cts
Stat150 spring06 markov_ctsStat150 spring06 markov_cts
Stat150 spring06 markov_ctsmbfrosh
 
Os lab file c programs
Os lab file c programsOs lab file c programs
Os lab file c programsKandarp Tiwari
 

Similaire à Lowest common ancestor (20)

Matlab assignment
Matlab assignmentMatlab assignment
Matlab assignment
 
Computer Graphics Lab File C Programs
Computer Graphics Lab File C ProgramsComputer Graphics Lab File C Programs
Computer Graphics Lab File C Programs
 
10CSL67 CG LAB PROGRAM 9
10CSL67 CG LAB PROGRAM 910CSL67 CG LAB PROGRAM 9
10CSL67 CG LAB PROGRAM 9
 
Os 2 cycle
Os 2 cycleOs 2 cycle
Os 2 cycle
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Numerical Method Assignment
Numerical Method AssignmentNumerical Method Assignment
Numerical Method Assignment
 
C programs
C programsC programs
C programs
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdf
 
Coding
CodingCoding
Coding
 
Aaex2 group2
Aaex2 group2Aaex2 group2
Aaex2 group2
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligence
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C Programs
 
Query Suggestion @ tokyotextmining#2
Query Suggestion @ tokyotextmining#2Query Suggestion @ tokyotextmining#2
Query Suggestion @ tokyotextmining#2
 
Graph for Coulomb damped oscillation
Graph for Coulomb damped oscillationGraph for Coulomb damped oscillation
Graph for Coulomb damped oscillation
 
Advanced Search Techniques
Advanced Search TechniquesAdvanced Search Techniques
Advanced Search Techniques
 
Ada boosting2
Ada boosting2Ada boosting2
Ada boosting2
 
Struct examples
Struct examplesStruct examples
Struct examples
 
Caropro
CaroproCaropro
Caropro
 
Stat150 spring06 markov_cts
Stat150 spring06 markov_ctsStat150 spring06 markov_cts
Stat150 spring06 markov_cts
 
Os lab file c programs
Os lab file c programsOs lab file c programs
Os lab file c programs
 

Plus de Shakil Ahmed (20)

Algorithm
AlgorithmAlgorithm
Algorithm
 
B-tree & R-tree
B-tree & R-treeB-tree & R-tree
B-tree & R-tree
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Command pattern
Command patternCommand pattern
Command pattern
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
iOS 5
iOS 5iOS 5
iOS 5
 
Ios development
Ios developmentIos development
Ios development
 
Graph
GraphGraph
Graph
 
Segment tree
Segment treeSegment tree
Segment tree
 
Tree & bst
Tree & bstTree & bst
Tree & bst
 
Trie tree
Trie treeTrie tree
Trie tree
 

Dernier

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 

Dernier (20)

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 

Lowest common ancestor

  • 1. Lowest Common Ancestor Md. Shakil Ahmed Software Engineer Astha it research & consultancy ltd. Dhaka, Bangladesh
  • 2. lowest common ancestor (LCA) • The lowest common ancestor (LCA) is a concept in graph theory and computer science. Let T be a rooted tree with n nodes. The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).
  • 4. LightOJ: 1101 - A Secret Mission There will be N evil cities (numbered by 1, 2, ..., N) connected by M bidirectional roads. There will be evil guards patrolling the roads. Since they are not much intelligent, the danger of travelling in each road is not the same. Alice is going to travel from city s to city t. You can safely assume that it's possible to travel from any city to another. John the legend programmer has estimated the danger of each road but since he is busy arranging contests, Alice is depending on you now. Danger of a path from city s to city t is defined as the maximum danger of any road on this path. As you are one of the most talented programmers, you will love to help Alice by finding the least dangerous paths to prevent Evil Jack from doing harms to the Judges.
  • 5. LightOJ: 1101 - A Secret Mission Input Input starts with an integer T (≤ 3), denoting the number of test cases. Each case contains two integers N, M (2 ≤ N ≤ 50000, 1 ≤ M ≤ 105) denoting the number of cities and roads. Each of the next M lines contains three integers: xi, yi, di (1 ≤ xi, yi ≤ N, xi ≠ yi, 1 ≤ di ≤ 104) - the cities connected by the ith road and its degree of danger. Next line contains an integer q (1 ≤ q ≤ 50000). Each of the next q lines contains two integers: si and ti (1 ≤ si, ti ≤ N, si ≠ ti). Output For each test case, print the case number first. Then for each query si ti, print the least dangerous path in a line.
  • 6. LightOJ: 1101 - A Secret Mission
  • 7. LightOJ: 1101 - A Secret Mission int cmp( const void *a, const void #include<stdio.h> *b ) #include <stdlib.h> { struct T T *p = (T *)a; { T *q = (T *)b; int x; return ( p->weight - q->weight ); int y; } int weight; }; int cmp1( const void *a, const void *b ) { struct TT TT *p = (TT *)a; { TT *q = (TT *)b; int x; int y; return ( p->x - q->x ); int weight; } };
  • 8. LightOJ: 1101 - A Secret Mission void dfs(int h1,int h2,int h3,int h4) T a[100009]; { TT A[100009]; PP[h1][0]=h2; MX[h1][0]=h3; int P[50009],ind[50009],N; L[h1]=h4; int Parent(long h1) { int h5; if(P[h1]==-1) return h1; for(h5=ind[h1];h5<N;h5++) { P[h1]=Parent(P[h1]); if(A[h5].x!=h1) return P[h1]; break; } if(A[h5].y!=h2) int PP[50009][20], MX[50009][20], dfs(A[h5].y,h1,A[h5].weight,h4+1); L[50009]; int cas,cas1,n,m,i,h1,h2,j,flag,q; } int q1,x,y,z,max; }
  • 9. LightOJ: 1101 - A Secret Mission int main() for(i=0;i<m;i++) { { h1 = Parent(a[i].x); scanf("%d",&cas); h2 = Parent(a[i].y); if(h1!=h2) for(cas1=1;cas1<=cas;cas1++) { { scanf("%d %d",&n,&m); P[h1]=h2; A[N].x = a[i].x; for(i=0;i<m;i++) A[N].y = a[i].y; scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].weight); A[N].weight = a[i].weight; qsort(a,m,sizeof(T),cmp); N++; A[N].x = a[i].y; for(i=1;i<=n;i++) A[N].y = a[i].x; P[i]=-1; A[N].weight = a[i].weight; N = 0; N++; } }
  • 10. LightOJ: 1101 - A Secret Mission qsort(A,N,sizeof(TT),cmp1); for(i=1;i<=n;i++) { for(i=1;i<=n;i++) if(PP[i][j-1]!=-1 && PP[PP[i][j-1]][j-1]!=-1) { { ind[i]=-1; PP[i][j]= PP[PP[i][j-1]][j-1]; } MX[i][j]=MX[i][j-1]; if(MX[i][j]<MX[PP[i][j-1]][j-1]) for(i=0;i<N;i++) MX[i][j]=MX[PP[i][j-1]][j-1]; if(ind[A[i].x]==-1) flag = 1; ind[A[i].x] = i; } else dfs(1,-1,-1,0); PP[i][j]=-1; } for(j=1;;j++) { if(flag==0) flag = 0; break; }
  • 11. LightOJ: 1101 - A Secret Mission scanf("%d",&q); while(L[x]!=L[y]) printf("Case %d:n",cas1); { for(q1=1;q1<=q;q1++) for(i=0;;i++) { { scanf("%d %d",&x,&y); if(PP[y][i]==-1||L[PP[y][i]]<L[x]) max = 0; { y = PP[y][i-1]; if(L[x]>L[y]) break; { } z = x; else if(MX[y][i]>max) x = y; max = MX[y][i]; y = z; } } }
  • 12. LightOJ: 1101 - A Secret Mission while(x!=y) else { { for(i=0;i<20;i++) x = PP[x][i-1]; y = PP[y][i-1]; { } if(PP[x][i]==PP[y][i]) break; { } if(i==0) else { { if(MX[x][i]>max) if(MX[x][i]>max) max = MX[x][i]; max = MX[x][i]; if(MX[y][i]>max) if(MX[y][i]>max) max = MX[y][i]; max = MX[y][i]; }} } printf("%dn",max); x = PP[x][i]; } } y = PP[y][i]; return 0; } }
  • 13. Sample • LightOJ: http://www.lightoj.com/volume_problemcate gory.php?user_id=3060&category=Range %20Minimum%20Query/Lowest%20Common %20Ancestor