SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Advanced Data Structure (using c#)

Md. Shakil Ahmed
Software Engineer
Astha it research & consultancy ltd.
Dhaka, Bangladesh
Introduction
Topic Focus:
• Trie Tree
• Segment Tree
• lowest common ancestor (LCA)
Trie Tree
• A trie is an ordered tree data structure that is
used to store an associative array where the
keys are usually strings.
Trie Tree
Use:
• Count Prefixes: This function will count the
  number of words in the dictionary that have a
  string prefix as prefix.
• Count Words: This function will count the
  number of words in the dictionary that match
  exactly with a given string word.
• Dictionary: It could be a good data structure for
  building a memory-efficient dictionary with fast
  lookups.
• Faster Than Hash Table: Looking up data in a trie
  is faster in the worst case, O(m) time, compared
  to an imperfect hash table.
Trie Tree
The next figure shows a trie with the
words
"tree", "trie", "algo", "assoc", "all", and
"also."
Trie Tree
• 1st word => tree
Trie Tree
• 2nd word => trie
Trie Tree
• 3rd word => algo
Trie Tree
• 4th word => assoc
Trie Tree
• 5th word => all
Trie Tree
• 6th word => also
Trie Tree
Problem
We have some Human name, we can add, delete &
  search some name.
=> If number of name is n = 10,00,000, we want to
  search or delete a name(k is the length of the
  name), then
1. If we use array, we need O(n*k) complexity.
2. If we sort the array & using binary search
    then, for search we need O(k * log n) but for
    delete we need O(n) complexity.
3. If we use trie, we need O(k) complexity for
    add, search & delete.
Solution
static int[] _count = new int[1000009];
static int[][] _child = new int[1000009][];static int N = 0;

static int AddElement(int root, string element, int position)
{ if (element.Length == position)
  { _count[root]++;
     return _count[root]; }
  else
  { if (_child[root][element[position] - 'a'] == -1)
     { _count[N] = 0;_child[N] = new int[26];
        for (int i = 0; i < 26; i++)
           _child[N][i] = -1;
        _child[root][element[position] - 'a'] = N;
        N++;
     }
   return AddElement(_child[root][element[position] - 'a'], element, position + 1);
  }
}
Solution
static void Main(string[] args)
     {
        _count[0] = 0;
        _child[0] = new int[26];
        for (int i = 0; i < 26; i++)
          _child[0][i] = -1;
        N = 1;

         while (true)
         {
           string input = Console.ReadLine();
           if (input == null)
              break;
           Console.WriteLine(AddElement(0, input.ToLower(), 0));
         }
     }
Segment Tree
• A segment tree is a heap-like data structure
that can be used for making update/query
operations upon array intervals in
logarithmical time.
• Query time: O(log n)
• Initialize time: O(2 * n)
• Update time: O(log n)
Segment Tree
Segment Tree

E very node v is characterized by tw o param eters

 B v : beginning of node's w orld (left end )

 E v : end of node's w orld (right end)



We define the segment tree for the interval [i, j] in the
following recursive manner:
the first node will hold the information for the interval [i, j]
if i<j the left and right son will hold the information for the
intervals [i, (i+j)/2] and [(i+j)/2+1, j]
Segment Tree
Segment Tree
Segment Tree
Segment Tree
• Initialize
Segment Tree
• Query For 2 to 6
Segment Tree
• Update Element 7 value to 7
Problem
  You are given n (1<=n<=100000) integers &
  100000 query. Each query you have to change
  a value of an element Or you have to given
  the minimum value of a range.
=> If we use array, then complexity q * n. For the
  above case it will take, 10000000000
  operation, that means 100 sec.
=> If we use segment tree then complexity is q *
  log (n). It will take 0.01 sec.
Solution
static int[] element = new int[100009];
 static int[] mini = new int[200009];static int[] left = new int[200009];static
int[] right = new int[200009];
 static int N = 0;

 static int Init(int start, int end)
 {
   if (start == end)
   { left[N] = -1;right[N] = -1;
      mini[N] = element[start];N++;
      return N - 1; }
   else
   { int temp = N; N++;
      left[temp] = Init(start, (start + end) / 2);
      right[temp] = Init((start + end) / 2 + 1, end);
      mini[temp] = mini[left[temp]];
      if (mini[temp] > mini[right[temp]])
         mini[temp] = mini[right[temp]];
      return temp;          }        }
Solution
static int RMQ(int root, int start, int end, int rootStart, int rootEnd)
     {
        if (start == rootStart && end == rootEnd)
            return mini[root];
        else if (end <= (rootStart + rootEnd) / 2)
            return RMQ(left[root], start, end, rootStart, (rootStart + rootEnd) / 2);
        else if ((rootStart + rootEnd) / 2 < start)
            return RMQ(right[root], start, end, (rootStart + rootEnd) / 2 + 1, rootEnd);
        else
        {
            int temp1 = RMQ(left[root], start, (rootStart + rootEnd) /
    2, rootStart, (rootStart + rootEnd) / 2);
            int temp2 = RMQ(right[root], (rootStart + rootEnd) / 2 + 1, end, (rootStart +
    rootEnd) / 2 + 1, rootEnd);
            if (temp1 > temp2)
               temp1 = temp2;
            return temp1;
        }}
Solution
static void Update(int root, int index, int value, int rootStart, int rootEnd)
     {
        if (rootStart == index && rootEnd == index)
           mini[root] = value;
        else
        {
           if (index <= (rootStart + rootEnd) / 2)
              Update(left[root], index, value, rootStart, (rootStart + rootEnd) / 2);
           else
              Update(right[root], index, value, (rootStart + rootEnd) / 2 +
    1, rootEnd);

            mini[root] = mini[left[root]];
            if (mini[root] > mini[right[root]])
               mini[root] = mini[right[root]];
        }
    }
Solution
static void Main(string[] args)                 for (int q1 = 1; q1 <= q; q1++)
     {                                                  {
        string input = Console.ReadLine();                input = Console.ReadLine();
                                                          string[] inputs = input.Split(' ');
       int n = Convert.ToInt32(input);                    int x = Convert.ToInt32(inputs[0]);
                                                          int y = Convert.ToInt32(inputs[1]);
       for (int i = 0; i < n; i++)                        int z = Convert.ToInt32(inputs[2]);
       {
         input = Console.ReadLine();                         if (x == 1)
         element[i] = Convert.ToInt32(input);                   Console.WriteLine(RMQ(0, y, z, 0, n
       }                                        - 1));
                                                             else
       N = 0;                                                  Update(0, y, z, 0, n - 1);
       Init(0, n - 1);                                   }
                                                     }
       input = Console.ReadLine();
       int q = Convert.ToInt32(input);
Segment Tree

• Segment trees are very powerful, not only
  because they can be used for RMQ(Range
  Minimum Query). They are a very flexible data
  structure, can solve even the dynamic version
  of RMQ problem, and have numerous
  applications in range searching problems.
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)
lowest common ancestor (LCA)
• We generate a table.
lowest common ancestor (LCA)
Node      2^0 Parent   2^1 Parent   2^2Parent
1         -1           -1           -1
2         1            -1           -1
3         1            -1           -1
4         2            1            -1
5         4            2            -1
6         3            1            -1
7         5            4            1
lowest common ancestor (LCA)

                   Node   Label
                   1      1
                   2      2
                   3      2
                   4      3
                   5      4
                   6      3
                   7      5
lowest common ancestor (LCA)
lowest common ancestor (LCA)
Problem
You live in a Big country where there are many bi-directional roads
connecting the cities. Since the people of the country are quite
intelligent, they designed the country such that there is exactly one
path to go from one city to another. A path consists of one or more
connected roads.
Here cities are denoted by integers and each road has a cost of
traveling. Now you are given the information about the Country. And
you are given some queries, each consists of two cities. You have to
find the longest road in the path from one city to another.
Input:
n (2 ≤ n ≤ 105) denoting the number of cities. Then there will be n-1
lines containing three integers each. They will be given in the form u v
w (1 ≤ u, v ≤ n, 0 < w ≤ 105, u ≠ v) meaning that there is a road
between u and v and the cost of the road is w.
The next line contains an integer q (1 ≤ q ≤ 25000) denoting the
number of queries. Each of the next q lines contains two integers x
and y (1 ≤ x, y ≤ n, x ≠ y).
Problem
Input:
6
                                    Output:
3 6 50                              300
2 5 30
2 4 300                             300
1 2 100
1 3 200                             30
4
14                                  200
46
25
35


      If we solve it only by parent up, then for easy query, we will
      need O(n) complexity.
      If we solve it by LCA, then for each query, we will need O(log n)
      complexity.
Solution
public class Edge
    { public int node;         public int cost;}
    static List<Edge>[] _connectedNodes = null;
    static int[] _dfsNumber = null;
    static int[][] _parent = null;
    static int[][] _maxCost = null;

    static void DFS(int node, int parent, int edgeCost, int dfsNumber)
    {
      _parent[node][0] = parent;
      _maxCost[node][0] = edgeCost;
      _dfsNumber[node] = dfsNumber;

      for (int i = 0; i < _connectedNodes[node].Count; i++)
        if (_dfsNumber[_connectedNodes[node][i].node] == -1)

   DFS(_connectedNodes[node][i].node, node, _connectedNodes[node][i].cost, dfsN
   umber + 1);
Solution
static void Main(string[] args)
{
string input = Console.ReadLine();         for (int i = 1; i < n; i++)
                                                   {
                                                      input = Console.ReadLine();
int n = Convert.ToInt32(input);                       string[] inputs = input.Split(' ');
_connectedNodes = new List<Edge>[n + 1];              int x = Convert.ToInt32(inputs[0]);
_dfsNumber = new int[n + 1];                          int y = Convert.ToInt32(inputs[1]);
_parent = new int[n + 1][];                           int z = Convert.ToInt32(inputs[2]);
_maxCost = new int[n + 1][];
                                                    _connectedNodes[x].Add(new Edge {
                                           node = y, cost = z });
for (int i = 1; i <= n; i++)                        _connectedNodes[y].Add(new Edge {
{                                          node = x, cost = z });
_dfsNumber[i] = -1;                              }
_parent[i] = new int[18];
                                           DFS(1, -1, 0, 1);
_maxCost[i] = new int[18];
_connectedNodes[i] = new List<Edge>();
}
Solution
for (int j = 1; ; j++)
        {
           bool flag = false;
           for (int i = 1; i <= n; i++)
           {
              if (_parent[i][j - 1] != -1 && _parent[_parent[i][j - 1]][j - 1] != -1)
              {
                 _parent[i][j] = _parent[_parent[i][j - 1]][j - 1];
                 _maxCost[i][j] = _maxCost[i][j - 1];
                 if (_maxCost[i][j] < _maxCost[_parent[i][j - 1]][j - 1])
                    _maxCost[i][j] = _maxCost[_parent[i][j - 1]][j - 1];
                 flag = true;
              }
              else
                 _parent[i][j] = -1;
           }

           if (!flag)break;
       }
Solution
input = Console.ReadLine();
       int q = Convert.ToInt32(input);

      for (int q1 = 1; q1 <= q; q1++)
      {
        input = Console.ReadLine();
        string[] inputs = input.Split(' ');
        int x = Convert.ToInt32(inputs[0]);
        int y = Convert.ToInt32(inputs[1]);

         int max = 0;

         if (_dfsNumber[x] > _dfsNumber[y])
         {
            int z = x;
            x = y;
            y = z;
         }
Solution
while (_dfsNumber[x] != _dfsNumber[y])
         {
           for (int i = 0; ; i++)
           {
             if (_parent[y][i] == -1 || _dfsNumber[_parent[y][i]] <
  _dfsNumber[x])
             {
                y = _parent[y][i - 1];
                break;
             }
             else
             {
                if (_maxCost[y][i] > max)
                   max = _maxCost[y][i];
             }
           }
         }
Solution
while (x != y)
          {                                          else
            for (int i = 0; i < 18; i++)                                    {
            {                                                                   if (_maxCost[x][i] > max)
               if (_parent[x][i] == _parent[y][i])
               {
                                                                                    max = _maxCost[x][i];
                  if (i == 0)                                                   if (_maxCost[y][i] > max)
                  {                                                                 max = _maxCost[y][i];
                     if (_maxCost[x][i] > max)                              }
                         max = _maxCost[x][i];                          }
                     if (_maxCost[y][i] > max)
                         max = _maxCost[y][i];
                                                                    }

                    x = _parent[x][i];                              Console.WriteLine(max);
                    y = _parent[y][i];                          }
                  }                                         }
                  else
                  {
                    x = _parent[x][i - 1];
                    y = _parent[y][i - 1];
                  }
                  break;
              }
Thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexityashishtinku
 
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
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
Chapter 9 ds
Chapter 9 dsChapter 9 ds
Chapter 9 dsHanif Durad
 
Algorithm
AlgorithmAlgorithm
Algorithmsultanarun
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithmspppepito86
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonshin
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues listsHarry Potter
 

Was ist angesagt? (20)

Lec4
Lec4Lec4
Lec4
 
Arrays
ArraysArrays
Arrays
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
 
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
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
Chapter 9 ds
Chapter 9 dsChapter 9 ds
Chapter 9 ds
 
Lec4
Lec4Lec4
Lec4
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Week7
Week7Week7
Week7
 
Lec1
Lec1Lec1
Lec1
 
algorithm unit 1
algorithm unit 1algorithm unit 1
algorithm unit 1
 
Java arrays
Java   arraysJava   arrays
Java arrays
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
 
Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
 

Andere mochten auch

Ads tactical interview questions and answers
Ads tactical interview questions and answersAds tactical interview questions and answers
Ads tactical interview questions and answersPaulScholes456
 
Disk scheduling algorithm.52
Disk scheduling algorithm.52Disk scheduling algorithm.52
Disk scheduling algorithm.52myrajendra
 
Interview Skills PowerPoint
Interview Skills PowerPointInterview Skills PowerPoint
Interview Skills PowerPointcking12
 
Process Scheduling
Process SchedulingProcess Scheduling
Process SchedulingAbhishek Nagar
 
Advances in agricultural technology
Advances in agricultural technologyAdvances in agricultural technology
Advances in agricultural technologyRonnie Z. Valenciano
 
CPU scheduling algorithms in OS
CPU scheduling algorithms in OSCPU scheduling algorithms in OS
CPU scheduling algorithms in OSharini0810
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating systemSara Ali
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock GalvinSonali Chauhan
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURESbca2010
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling AlgorithmsShubhashish Punj
 
Operating system and its function
Operating system and its functionOperating system and its function
Operating system and its functionNikhi Jain
 
Roles and problems of agriculture
Roles and problems of agricultureRoles and problems of agriculture
Roles and problems of agricultureRebam Jilani
 
Operating Systems
Operating SystemsOperating Systems
Operating SystemsHarshith Meela
 
Presentation on operating system
 Presentation on operating system Presentation on operating system
Presentation on operating systemNitish Xavier Tirkey
 
Operating system overview concepts ppt
Operating system overview concepts pptOperating system overview concepts ppt
Operating system overview concepts pptRajendraPrasad Alladi
 
Operating system.ppt (1)
Operating system.ppt (1)Operating system.ppt (1)
Operating system.ppt (1)Vaibhav Bajaj
 
Indian agriculture
Indian agricultureIndian agriculture
Indian agriculturekanishk102
 
agriculture ppt
 agriculture ppt agriculture ppt
agriculture ppticon66rt
 

Andere mochten auch (20)

Ads tactical interview questions and answers
Ads tactical interview questions and answersAds tactical interview questions and answers
Ads tactical interview questions and answers
 
Disk scheduling algorithm.52
Disk scheduling algorithm.52Disk scheduling algorithm.52
Disk scheduling algorithm.52
 
Interview Skills PowerPoint
Interview Skills PowerPointInterview Skills PowerPoint
Interview Skills PowerPoint
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Scheduling
 
Advances in agricultural technology
Advances in agricultural technologyAdvances in agricultural technology
Advances in agricultural technology
 
Deadlock ppt
Deadlock ppt Deadlock ppt
Deadlock ppt
 
CPU scheduling algorithms in OS
CPU scheduling algorithms in OSCPU scheduling algorithms in OS
CPU scheduling algorithms in OS
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock Galvin
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
 
Operating system and its function
Operating system and its functionOperating system and its function
Operating system and its function
 
Roles and problems of agriculture
Roles and problems of agricultureRoles and problems of agriculture
Roles and problems of agriculture
 
Operating Systems
Operating SystemsOperating Systems
Operating Systems
 
Presentation on operating system
 Presentation on operating system Presentation on operating system
Presentation on operating system
 
Operating system overview concepts ppt
Operating system overview concepts pptOperating system overview concepts ppt
Operating system overview concepts ppt
 
Operating system.ppt (1)
Operating system.ppt (1)Operating system.ppt (1)
Operating system.ppt (1)
 
Indian agriculture
Indian agricultureIndian agriculture
Indian agriculture
 
agriculture ppt
 agriculture ppt agriculture ppt
agriculture ppt
 

Ă„hnlich wie Advanced data structure

Datastructure tree
Datastructure treeDatastructure tree
Datastructure treerantd
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqPradeep Bisht
 
Advanced Search Techniques
Advanced Search TechniquesAdvanced Search Techniques
Advanced Search TechniquesShakil Ahmed
 
TeraSort
TeraSortTeraSort
TeraSortTung D. Le
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexityshowkat27
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Ra'Fat Al-Msie'deen
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdfSrinivasaReddyPolamR
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptxSajalFayyaz
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docSrikrishnaVundavalli
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingzukun
 
PVEB Tree.pptx
PVEB Tree.pptxPVEB Tree.pptx
PVEB Tree.pptxSanthosh A
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Big o notation
Big o notationBig o notation
Big o notationhamza mushtaq
 
Big o notation
Big o notationBig o notation
Big o notationhamza mushtaq
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0BG Java EE Course
 
Segment tree
Segment treeSegment tree
Segment treeShakil Ahmed
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfShiwani Gupta
 

Ă„hnlich wie Advanced data structure (20)

Datastructure tree
Datastructure treeDatastructure tree
Datastructure tree
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
 
Advanced Search Techniques
Advanced Search TechniquesAdvanced Search Techniques
Advanced Search Techniques
 
TeraSort
TeraSortTeraSort
TeraSort
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdf
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Review session2
Review session2Review session2
Review session2
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptx
 
Lec35
Lec35Lec35
Lec35
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
 
PVEB Tree.pptx
PVEB Tree.pptxPVEB Tree.pptx
PVEB Tree.pptx
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Big o notation
Big o notationBig o notation
Big o notation
 
Big o notation
Big o notationBig o notation
Big o notation
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Segment tree
Segment treeSegment tree
Segment tree
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
 

Mehr von Shakil Ahmed

B-tree & R-tree
B-tree & R-treeB-tree & R-tree
B-tree & R-treeShakil Ahmed
 
Prototype pattern
Prototype patternPrototype pattern
Prototype patternShakil Ahmed
 
Observer pattern
Observer patternObserver pattern
Observer patternShakil Ahmed
 
Mediator pattern
Mediator patternMediator pattern
Mediator patternShakil Ahmed
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight patternShakil Ahmed
 
Facade pattern
Facade patternFacade pattern
Facade patternShakil Ahmed
 
Composite pattern
Composite patternComposite pattern
Composite patternShakil Ahmed
 
Command pattern
Command patternCommand pattern
Command patternShakil Ahmed
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibilityShakil Ahmed
 
Builder pattern
Builder patternBuilder pattern
Builder patternShakil Ahmed
 
Bridge pattern
Bridge patternBridge pattern
Bridge patternShakil Ahmed
 
Adapter pattern
Adapter patternAdapter pattern
Adapter patternShakil Ahmed
 
Proxy pattern
Proxy patternProxy pattern
Proxy patternShakil Ahmed
 
Ios development
Ios developmentIos development
Ios developmentShakil Ahmed
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingShakil Ahmed
 

Mehr von 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
 
Tree & bst
Tree & bstTree & bst
Tree & bst
 
Trie tree
Trie treeTrie tree
Trie tree
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 

KĂĽrzlich hochgeladen

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

KĂĽrzlich hochgeladen (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 

Advanced data structure

  • 1. Advanced Data Structure (using c#) Md. Shakil Ahmed Software Engineer Astha it research & consultancy ltd. Dhaka, Bangladesh
  • 2. Introduction Topic Focus: • Trie Tree • Segment Tree • lowest common ancestor (LCA)
  • 3. Trie Tree • A trie is an ordered tree data structure that is used to store an associative array where the keys are usually strings.
  • 4. Trie Tree Use: • Count Prefixes: This function will count the number of words in the dictionary that have a string prefix as prefix. • Count Words: This function will count the number of words in the dictionary that match exactly with a given string word. • Dictionary: It could be a good data structure for building a memory-efficient dictionary with fast lookups. • Faster Than Hash Table: Looking up data in a trie is faster in the worst case, O(m) time, compared to an imperfect hash table.
  • 5. Trie Tree The next figure shows a trie with the words "tree", "trie", "algo", "assoc", "all", and "also."
  • 6. Trie Tree • 1st word => tree
  • 7. Trie Tree • 2nd word => trie
  • 8. Trie Tree • 3rd word => algo
  • 9. Trie Tree • 4th word => assoc
  • 10. Trie Tree • 5th word => all
  • 11. Trie Tree • 6th word => also
  • 13. Problem We have some Human name, we can add, delete & search some name. => If number of name is n = 10,00,000, we want to search or delete a name(k is the length of the name), then 1. If we use array, we need O(n*k) complexity. 2. If we sort the array & using binary search then, for search we need O(k * log n) but for delete we need O(n) complexity. 3. If we use trie, we need O(k) complexity for add, search & delete.
  • 14. Solution static int[] _count = new int[1000009]; static int[][] _child = new int[1000009][];static int N = 0; static int AddElement(int root, string element, int position) { if (element.Length == position) { _count[root]++; return _count[root]; } else { if (_child[root][element[position] - 'a'] == -1) { _count[N] = 0;_child[N] = new int[26]; for (int i = 0; i < 26; i++) _child[N][i] = -1; _child[root][element[position] - 'a'] = N; N++; } return AddElement(_child[root][element[position] - 'a'], element, position + 1); } }
  • 15. Solution static void Main(string[] args) { _count[0] = 0; _child[0] = new int[26]; for (int i = 0; i < 26; i++) _child[0][i] = -1; N = 1; while (true) { string input = Console.ReadLine(); if (input == null) break; Console.WriteLine(AddElement(0, input.ToLower(), 0)); } }
  • 16. Segment Tree • A segment tree is a heap-like data structure that can be used for making update/query operations upon array intervals in logarithmical time. • Query time: O(log n) • Initialize time: O(2 * n) • Update time: O(log n)
  • 18. Segment Tree E very node v is characterized by tw o param eters B v : beginning of node's w orld (left end ) E v : end of node's w orld (right end) We define the segment tree for the interval [i, j] in the following recursive manner: the first node will hold the information for the interval [i, j] if i<j the left and right son will hold the information for the intervals [i, (i+j)/2] and [(i+j)/2+1, j]
  • 24. Segment Tree • Update Element 7 value to 7
  • 25. Problem You are given n (1<=n<=100000) integers & 100000 query. Each query you have to change a value of an element Or you have to given the minimum value of a range. => If we use array, then complexity q * n. For the above case it will take, 10000000000 operation, that means 100 sec. => If we use segment tree then complexity is q * log (n). It will take 0.01 sec.
  • 26. Solution static int[] element = new int[100009]; static int[] mini = new int[200009];static int[] left = new int[200009];static int[] right = new int[200009]; static int N = 0; static int Init(int start, int end) { if (start == end) { left[N] = -1;right[N] = -1; mini[N] = element[start];N++; return N - 1; } else { int temp = N; N++; left[temp] = Init(start, (start + end) / 2); right[temp] = Init((start + end) / 2 + 1, end); mini[temp] = mini[left[temp]]; if (mini[temp] > mini[right[temp]]) mini[temp] = mini[right[temp]]; return temp; } }
  • 27. Solution static int RMQ(int root, int start, int end, int rootStart, int rootEnd) { if (start == rootStart && end == rootEnd) return mini[root]; else if (end <= (rootStart + rootEnd) / 2) return RMQ(left[root], start, end, rootStart, (rootStart + rootEnd) / 2); else if ((rootStart + rootEnd) / 2 < start) return RMQ(right[root], start, end, (rootStart + rootEnd) / 2 + 1, rootEnd); else { int temp1 = RMQ(left[root], start, (rootStart + rootEnd) / 2, rootStart, (rootStart + rootEnd) / 2); int temp2 = RMQ(right[root], (rootStart + rootEnd) / 2 + 1, end, (rootStart + rootEnd) / 2 + 1, rootEnd); if (temp1 > temp2) temp1 = temp2; return temp1; }}
  • 28. Solution static void Update(int root, int index, int value, int rootStart, int rootEnd) { if (rootStart == index && rootEnd == index) mini[root] = value; else { if (index <= (rootStart + rootEnd) / 2) Update(left[root], index, value, rootStart, (rootStart + rootEnd) / 2); else Update(right[root], index, value, (rootStart + rootEnd) / 2 + 1, rootEnd); mini[root] = mini[left[root]]; if (mini[root] > mini[right[root]]) mini[root] = mini[right[root]]; } }
  • 29. Solution static void Main(string[] args) for (int q1 = 1; q1 <= q; q1++) { { string input = Console.ReadLine(); input = Console.ReadLine(); string[] inputs = input.Split(' '); int n = Convert.ToInt32(input); int x = Convert.ToInt32(inputs[0]); int y = Convert.ToInt32(inputs[1]); for (int i = 0; i < n; i++) int z = Convert.ToInt32(inputs[2]); { input = Console.ReadLine(); if (x == 1) element[i] = Convert.ToInt32(input); Console.WriteLine(RMQ(0, y, z, 0, n } - 1)); else N = 0; Update(0, y, z, 0, n - 1); Init(0, n - 1); } } input = Console.ReadLine(); int q = Convert.ToInt32(input);
  • 30. Segment Tree • Segment trees are very powerful, not only because they can be used for RMQ(Range Minimum Query). They are a very flexible data structure, can solve even the dynamic version of RMQ problem, and have numerous applications in range searching problems.
  • 31. 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).
  • 33. lowest common ancestor (LCA) • We generate a table.
  • 34. lowest common ancestor (LCA) Node 2^0 Parent 2^1 Parent 2^2Parent 1 -1 -1 -1 2 1 -1 -1 3 1 -1 -1 4 2 1 -1 5 4 2 -1 6 3 1 -1 7 5 4 1
  • 35. lowest common ancestor (LCA) Node Label 1 1 2 2 3 2 4 3 5 4 6 3 7 5
  • 38. Problem You live in a Big country where there are many bi-directional roads connecting the cities. Since the people of the country are quite intelligent, they designed the country such that there is exactly one path to go from one city to another. A path consists of one or more connected roads. Here cities are denoted by integers and each road has a cost of traveling. Now you are given the information about the Country. And you are given some queries, each consists of two cities. You have to find the longest road in the path from one city to another. Input: n (2 ≤ n ≤ 105) denoting the number of cities. Then there will be n-1 lines containing three integers each. They will be given in the form u v w (1 ≤ u, v ≤ n, 0 < w ≤ 105, u ≠ v) meaning that there is a road between u and v and the cost of the road is w. The next line contains an integer q (1 ≤ q ≤ 25000) denoting the number of queries. Each of the next q lines contains two integers x and y (1 ≤ x, y ≤ n, x ≠ y).
  • 39. Problem Input: 6 Output: 3 6 50 300 2 5 30 2 4 300 300 1 2 100 1 3 200 30 4 14 200 46 25 35 If we solve it only by parent up, then for easy query, we will need O(n) complexity. If we solve it by LCA, then for each query, we will need O(log n) complexity.
  • 40. Solution public class Edge { public int node; public int cost;} static List<Edge>[] _connectedNodes = null; static int[] _dfsNumber = null; static int[][] _parent = null; static int[][] _maxCost = null; static void DFS(int node, int parent, int edgeCost, int dfsNumber) { _parent[node][0] = parent; _maxCost[node][0] = edgeCost; _dfsNumber[node] = dfsNumber; for (int i = 0; i < _connectedNodes[node].Count; i++) if (_dfsNumber[_connectedNodes[node][i].node] == -1) DFS(_connectedNodes[node][i].node, node, _connectedNodes[node][i].cost, dfsN umber + 1);
  • 41. Solution static void Main(string[] args) { string input = Console.ReadLine(); for (int i = 1; i < n; i++) { input = Console.ReadLine(); int n = Convert.ToInt32(input); string[] inputs = input.Split(' '); _connectedNodes = new List<Edge>[n + 1]; int x = Convert.ToInt32(inputs[0]); _dfsNumber = new int[n + 1]; int y = Convert.ToInt32(inputs[1]); _parent = new int[n + 1][]; int z = Convert.ToInt32(inputs[2]); _maxCost = new int[n + 1][]; _connectedNodes[x].Add(new Edge { node = y, cost = z }); for (int i = 1; i <= n; i++) _connectedNodes[y].Add(new Edge { { node = x, cost = z }); _dfsNumber[i] = -1; } _parent[i] = new int[18]; DFS(1, -1, 0, 1); _maxCost[i] = new int[18]; _connectedNodes[i] = new List<Edge>(); }
  • 42. Solution for (int j = 1; ; j++) { bool flag = false; for (int i = 1; i <= n; i++) { if (_parent[i][j - 1] != -1 && _parent[_parent[i][j - 1]][j - 1] != -1) { _parent[i][j] = _parent[_parent[i][j - 1]][j - 1]; _maxCost[i][j] = _maxCost[i][j - 1]; if (_maxCost[i][j] < _maxCost[_parent[i][j - 1]][j - 1]) _maxCost[i][j] = _maxCost[_parent[i][j - 1]][j - 1]; flag = true; } else _parent[i][j] = -1; } if (!flag)break; }
  • 43. Solution input = Console.ReadLine(); int q = Convert.ToInt32(input); for (int q1 = 1; q1 <= q; q1++) { input = Console.ReadLine(); string[] inputs = input.Split(' '); int x = Convert.ToInt32(inputs[0]); int y = Convert.ToInt32(inputs[1]); int max = 0; if (_dfsNumber[x] > _dfsNumber[y]) { int z = x; x = y; y = z; }
  • 44. Solution while (_dfsNumber[x] != _dfsNumber[y]) { for (int i = 0; ; i++) { if (_parent[y][i] == -1 || _dfsNumber[_parent[y][i]] < _dfsNumber[x]) { y = _parent[y][i - 1]; break; } else { if (_maxCost[y][i] > max) max = _maxCost[y][i]; } } }
  • 45. Solution while (x != y) { else for (int i = 0; i < 18; i++) { { if (_maxCost[x][i] > max) if (_parent[x][i] == _parent[y][i]) { max = _maxCost[x][i]; if (i == 0) if (_maxCost[y][i] > max) { max = _maxCost[y][i]; if (_maxCost[x][i] > max) } max = _maxCost[x][i]; } if (_maxCost[y][i] > max) max = _maxCost[y][i]; } x = _parent[x][i]; Console.WriteLine(max); y = _parent[y][i]; } } } else { x = _parent[x][i - 1]; y = _parent[y][i - 1]; } break; }