SlideShare a Scribd company logo
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!

More Related Content

What's hot

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 Expressions
Chris Eargle
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
Chapter 9 ds
Chapter 9 dsChapter 9 ds
Chapter 9 ds
Hanif Durad
 
Lec4
Lec4Lec4
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
pppepito86
 
Week7
Week7Week7
Lec1
Lec1Lec1
Java arrays
Java   arraysJava   arrays
Java arrays
Maneesha Caldera
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
shin
 
Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
Khirulnizam Abd Rahman
 
Stacks queues lists
Stacks queues listsStacks queues lists
Stacks queues lists
Harry Potter
 

What's hot (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
 

Viewers also liked

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 PowerPoint
cking12
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Scheduling
Abhishek 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 OS
harini0810
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
Sara Ali
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock GalvinSonali Chauhan
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
bca2010
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
Shubhashish 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 system overview concepts ppt
Operating system overview concepts pptOperating system overview concepts ppt
Operating system overview concepts ppt
RajendraPrasad 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 agriculture
kanishk102
 
agriculture ppt
 agriculture ppt agriculture ppt
agriculture ppt
icon66rt
 

Viewers also liked (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
 

Similar to Advanced data structure

Datastructure tree
Datastructure treeDatastructure tree
Datastructure tree
rantd
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
Pradeep Bisht
 
Advanced Search Techniques
Advanced Search TechniquesAdvanced Search Techniques
Advanced Search Techniques
Shakil Ahmed
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
showkat27
 
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.pdf
SrinivasaReddyPolamR
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
Saurabh Singh
 
Review session2
Review session2Review session2
Review session2
NEEDY12345
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptx
SajalFayyaz
 
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
SrikrishnaVundavalli
 
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.pptx
Santhosh A
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Big o notation
Big o notationBig o notation
Big o notation
hamza mushtaq
 
Big o notation
Big o notationBig o notation
Big o notation
hamza mushtaq
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
Segment tree
Segment treeSegment tree
Segment tree
Shakil Ahmed
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
Shiwani Gupta
 

Similar to 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
 

More from Shakil Ahmed

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

More from 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
 

Recently uploaded

World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
Landownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptxLandownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptx
JezreelCabil2
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 

Recently uploaded (20)

World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
Landownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptxLandownership in the Philippines under the Americans-2-pptx.pptx
Landownership in the Philippines under the Americans-2-pptx.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 

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; }