-
Notifications
You must be signed in to change notification settings - Fork 6
/
InterviewUsefulCode.cpp
5674 lines (4495 loc) · 139 KB
/
InterviewUsefulCode.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <bits/stdc++.h>
using namespace std;
// structure for Binary Node
struct Node {
int key;
struct Node *right, *left;
};
Node* newNode(int num)
{
Node* temp = new Node;
temp->key = num;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// To create a Tree with n levels. We always
// insert new node to left if it is less than
// previous value.
Node* createNLevelTree(int arr[], int n)
{
Node* root = newNode(arr[0]);
Node* temp = root;
for (int i = 1; i < n; i++) {
if (temp->key > arr[i]) {
temp->left = newNode(arr[i]);
temp = temp->left;
}
else {
temp->right = newNode(arr[i]);
temp = temp->right;
}
}
return root;
}
// Please refer below post for details of this
// function.
// https:// www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
bool isBST(Node* root, int min, int max)
{
if (root == NULL)
return true;
if (root->key < min || root->key > max)
return false;
// Allow only distinct values
return (isBST(root->left, min,
(root->key) - 1)
&& isBST(root->right,
(root->key) + 1, max));
}
// Returns tree if given array of size n can
// represent a BST of n levels.
bool canRepresentNLevelBST(int arr[], int n)
{
Node* root = createNLevelTree(arr, n);
return isBST(root, INT_MIN, INT_MAX);
}
//Check if a given Binary Tree is Heap
/* This function counts the number of nodes in a binary tree */
unsigned int countNodes(struct Node* root)
{
if (root == NULL)
return (0);
return (1 + countNodes(root->left) + countNodes(root->right));
}
/* This function checks if the binary tree is complete or not */
bool isCompleteUtil (struct Node* root, unsigned int index,
unsigned int number_nodes)
{
// An empty tree is complete
if (root == NULL)
return (true);
// If index assigned to current node is more than
// number of nodes in tree, then tree is not complete
if (index >= number_nodes)
return (false);
// Recur for left and right subtrees
return (isCompleteUtil(root->left, 2*index + 1, number_nodes) &&
isCompleteUtil(root->right, 2*index + 2, number_nodes));
}
// This Function checks the heap property in the tree.
bool isHeapUtil(struct Node* root)
{
// Base case : single node satisfies property
if (root->left == NULL && root->right == NULL)
return (true);
// node will be in second last level
if (root->right == NULL)
{
// check heap property at Node
// No recursive call , because no need to check last level
return (root->key >= root->left->key);
}
else
{
// Check heap property at Node and
// Recursive check heap property at left and right subtree
if (root->key >= root->left->key &&
root->key >= root->right->key)
return ((isHeapUtil(root->left)) &&
(isHeapUtil(root->right)));
else
return (false);
}
}
// Function to check binary tree is a Heap or Not.
bool isHeap(struct Node* root)
{
// These two are used in isCompleteUtil()
unsigned int node_count = countNodes(root);
unsigned int index = 0;
if (isCompleteUtil(root, index, node_count) && isHeapUtil(root))
return true;
return false;
}
// A recursive function to construct BST from pre[]. preIndex is used
// to keep track of index in pre[].
struct node* constructTreeUtil( int pre[], int* preIndex, int key,
int min, int max, int size )
{
// Base case
if( *preIndex >= size )
return NULL;
struct node* root = NULL;
// If current element of pre[] is in range, then
// only it is part of current subtree
if( key > min && key < max )
{
// Allocate memory for root of this subtree and increment *preIndex
root = newNode ( key );
*preIndex = *preIndex + 1;
if (*preIndex < size)
{
// Contruct the subtree under root
// All nodes which are in range {min .. key} will go in left
// subtree, and first such node will be root of left subtree.
root->left = constructTreeUtil( pre, preIndex, pre[*preIndex],
min, key, size );
// All nodes which are in range {key..max} will go in right
// subtree, and first such node will be root of right subtree.
root->right = constructTreeUtil( pre, preIndex, pre[*preIndex],
key, max, size );
}
}
return root;
}
// The main function to construct BST from given preorder traversal.
// This function mainly uses constructTreeUtil()
struct node *constructTree (int pre[], int size)
{
int preIndex = 0;
return constructTreeUtil ( pre, &preIndex, pre[0], INT_MIN, INT_MAX, size );
}
//Construct a Binary Search Tree from given postorder
struct node* constructTreeUtil(int post[], int* postIndex,
int key, int min, int max, int size)
{
// Base case
if (*postIndex < 0)
return NULL;
struct node* root = NULL;
// If current element of post[] is in range, then
// only it is part of current subtree
if (key > min && key < max)
{
// Allocate memory for root of this subtree and decrement
// *postIndex
root = newNode(key);
*postIndex = *postIndex - 1;
if (*postIndex >= 0)
{
// All nodes which are in range {key..max} will go in right
// subtree, and first such node will be root of right subtree.
root->right = constructTreeUtil(post, postIndex, post[*postIndex],
key, max, size );
// Contruct the subtree under root
// All nodes which are in range {min .. key} will go in left
// subtree, and first such node will be root of left subtree.
root->left = constructTreeUtil(post, postIndex, post[*postIndex],
min, key, size );
}
}
return root;
}
// The main function to construct BST from given postorder
// traversal. This function mainly uses constructTreeUtil()
struct node *constructTree (int post[], int size)
{
int postIndex = size-1;
return constructTreeUtil(post, &postIndex, post[postIndex],
INT_MIN, INT_MAX, size);
}
Query of type 1 :
Find the range sum on segment tree for output query where range is exit time and entry
time of the rooted tree node. Deduce that the answer is always twice the expected answer
because each node is added twice in segment tree. So reduce the answer by half.
Query of type 2 :
For update query, update the leaf node of segment tree at the entry time and exit time of
the rooted tree node.
Below is the implementation of above approach :
// C++ program for implementation of
// Euler Tour | Subtree Sum.
#include <bits/stdc++.h>
using namespace std;
vector<int> v[1001];
vector<int> s;
int seg[1001] = { 0 };
// Value/Weight of each node of tree,
// value of 0th(no such node) node is 0.
int ar[] = { 0, 1, 2, 3, 4, 5, 6 };
int vertices = 6;
int edges = 5;
// A recursive function that constructs
// Segment Tree for array ar[] = { }.
// 'pos' is index of current node
// in segment tree seg[].
int segment(int low, int high, int pos)
{
if (high == low) {
seg[pos] = ar[s[low]];
}
else {
int mid = (low + high) / 2;
segment(low, mid, 2 * pos);
segment(mid + 1, high, 2 * pos + 1);
seg[pos] = seg[2 * pos] + seg[2 * pos + 1];
}
}
/* Return sum of elements in range
from index l to r . It uses the
seg[] array created using segment()
function. 'pos' is index of current
node in segment tree seg[].
*/
int query(int node, int start,
int end, int l, int r)
{
if (r < start || end < l) {
return 0;
}
if (l <= start && end <= r) {
return seg[node];
}
int mid = (start + end) / 2;
int p1 = query(2 * node, start,
mid, l, r);
int p2 = query(2 * node + 1, mid + 1,
end, l, r);
return (p1 + p2);
}
/* A recursive function to update the
nodes which have the given index in
their range. The following are
parameters pos --> index of current
node in segment tree seg[]. idx -->
index of the element to be updated.
This index is in input array.
val --> Value to be change at node idx
*/
int update(int pos, int low, int high,
int idx, int val)
{
if (low == high) {
seg[pos] = val;
}
else {
int mid = (low + high) / 2;
if (low <= idx && idx <= mid) {
update(2 * pos, low, mid,
idx, val);
}
else {
update(2 * pos + 1, mid + 1,
high, idx, val);
}
seg[pos] = seg[2 * pos] + seg[2 * pos + 1];
}
}
/* A recursive function to form array
ar[] from a directed tree .
*/
int dfs(int root)
{
// pushing each node in vector s
s.push_back(root);
if (v[root].size() == 0)
return root;
for (int i = 0; i < v[root].size(); i++) {
int temp = dfs(v[root][i]);
s.push_back(temp);
}
return root;
}
// Driver program to test above functions
int main()
{
// Edges between the nodes
v[1].push_back(2);
v[1].push_back(3);
v[2].push_back(6);
v[2].push_back(5);
v[3].push_back(4);
// Calling dfs function.
int temp = dfs(1);
s.push_back(temp);
// Storing entry time and exit
// time of each node
vector<pair<int, int> > p;
for (int i = 0; i <= vertices; i++)
p.push_back(make_pair(0, 0));
for (int i = 0; i < s.size(); i++) {
if (p[s[i]].first == 0)
p[s[i]].first = i + 1;
else
p[s[i]].second = i + 1;
}
// Build segment tree from array ar[].
segment(0, s.size() - 1, 1);
// query of type 1 return the
// sum of subtree at node 1.
int node = 1;
int e = p[node].first;
int f = p[node].second;
int ans = query(1, 1, s.size(), e, f);
// print the sum of subtree
cout << "Subtree sum of node " << node << " is : " << (ans / 2) << endl;
// query of type 2 return update
// the subtree at node 6.
int val = 10;
node = 6;
e = p[node].first;
f = p[node].second;
update(1, 1, s.size(), e, val);
update(1, 1, s.size(), f, val);
// query of type 1 return the
// sum of subtree at node 2.
node = 2;
e = p[node].first;
f = p[node].second;
ans = query(1, 1, s.size(), e, f);
// print the sum of subtree
cout << "Subtree sum of node " << node << " is : " << (ans / 2) << endl;
return 0;
}
Output:
Subtree sum of node 1 is : 21
Subtree sum of node 2 is : 17
Time Complexity : O(q*log(n))
// This function clones a given linked list
// in O(1) space
Node* clone(Node *start)
{
Node* curr = start, *temp;
// insert additional node after
// every node of original list
while (curr)
{
temp = curr->next;
// Inserting node
curr->next = new Node(curr->data);
curr->next->next = temp;
curr = temp;
}
curr = start;
// adjust the random pointers of the
// newly added nodes
while (curr)
{
curr->next->random = curr->random->next;
// move to the next newly added node by
// skipping an original node
curr = curr->next?curr->next->next:curr->next;
}
Node* original = start, *copy = start->next;
// save the start of copied linked list
temp = copy;
// now separate the original list and copied list
while (original && copy)
{
original->next =
original->next? original->next->next : original->next;
copy->next = copy->next?copy->next->next:copy->next;
original = original->next;
copy = copy->next;
}
return temp;
}
// Driver code
int main()
{
Node* start = new Node(1);
start->next = new Node(2);
#include <bits/stdc++.h>
int _mergeSort(int arr[], int temp[], int left, int right);
int merge(int arr[], int temp[], int left, int mid, int right);
/* This function sorts the input array and returns the
number of inversions in the array */
int mergeSort(int arr[], int array_size)
{
int* temp = (int*)malloc(sizeof(int) * array_size);
return _mergeSort(arr, temp, 0, array_size - 1);
}
/* An auxiliary recursive function that sorts the input array and
returns the number of inversions in the array. */
int _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left) {
/* Divide the array into two parts and call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left) / 2;
/* Inversion count will be sum of inversions in left-part, right-part
and number of inversions in merging */
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid + 1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}
/* This funt merges two sorted arrays and returns inversion count in
the arrays.*/
int merge(int arr[], int temp[], int left, int mid, int right)
{
int i, j, k;
int inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* j is index for right subarray*/
k = left; /* k is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else {
temp[k++] = arr[j++];
/*this is tricky -- see above explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
/* Driver program to test above functions */
int main(int argv, char** args)
{
int arr[] = { 1, 20, 6, 4, 5 };
printf(" Number of inversions are %d \n", mergeSort(arr, 5));
getchar();
return 0;
}
// We can use stl container list as a double
// ended queue to store the cache keys, with
// the descending time of reference from front
// to back and a set container to check presence
// of a key. But to fetch the address of the key
// in the list using find(), it takes O(N) time.
// This can be optimized by storing a reference
// (iterator) to each key in a hash map.
#include <bits/stdc++.h>
using namespace std;
class LRUCache {
// store keys of cache
list<int> dq;
// store references of key in cache
unordered_map<int, list<int>::iterator> ma;
int csize; // maximum capacity of cache
public:
LRUCache(int);
void refer(int);
void display();
};
// Declare the size
LRUCache::LRUCache(int n)
{
csize = n;
}
// Refers key x with in the LRU cache
void LRUCache::refer(int x)
{
// not present in cache
if (ma.find(x) == ma.end()) {
// cache is full
if (dq.size() == csize) {
// delete least recently used element
int last = dq.back();
// Pops the last elmeent
dq.pop_back();
// Erase the last
ma.erase(last);
}
}
// present in cache
else
dq.erase(ma[x]);
// update reference
dq.push_front(x);
ma[x] = dq.begin();
}
// Function to display contents of cache
void LRUCache::display()
{
// Iterate in the deque and print
// all the elements in it
for (auto it = dq.begin(); it != dq.end();
it++)
cout << (*it) << " ";
cout << endl;
}
// Driver Code
int main()
{
LRUCache ca(4);
ca.refer(1);
ca.refer(2);
ca.refer(3);
ca.refer(1);
ca.refer(4);
ca.refer(5);
ca.display();
return 0;
}
// mirror of a tree
void mirror(struct node* node)
{
if (node)
{
struct node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
// Maximum Width of Binary Tree
// In this method we create a temporary array count[] of size equal to the height of tree. We initialize all values in count as 0. We traverse the tree using preorder traversal and fill the entries in count so that the count array contains count of nodes at each level in Binary Tree.
int getMaxWidth(struct node* root)
{
int width;
int h = height(root);
// Create an array that will store count of nodes at each level
int *count = (int *)calloc(sizeof(int), h);
int level = 0;
// Fill the count array using preorder traversal
getMaxWidthRecur(root, count, level);
// Return the maximum value from count array
return getMax(count, h);
}
// A function that fills count array with count of nodes at every
// level of given binary tree
void getMaxWidthRecur(struct node *root, int count[], int level)
{
if(root)
{
count[level]++;
getMaxWidthRecur(root->left, count, level+1);
getMaxWidthRecur(root->right, count, level+1);
}
}
// UTILITY FUNCTIONS
// Compute the "height" of a tree -- the number of
//nodes along the longest path from the root node
//down to the farthest leaf node.
//int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lHeight = height(node->left);
int rHeight = height(node->right);
/* use the larger one */
return (lHeight > rHeight)? (lHeight+1): (rHeight+1);
}
}
//Diameter of a binary tree
int diameter(struct node * tree)
{
/* base case where tree is empty */
if (tree == 0)
return 0;
/* get the height of left and right sub-trees */
int lheight = maxDepth(tree->left);
int rheight = maxDepth(tree->right);
/* get the diameter of left and right sub-trees */
int ldiameter = diameter(tree->left);
int rdiameter = diameter(tree->right);
/* Return max of following three
1) Diameter of left subtree
2) Diameter of right subtree
3) Height of left subtree + height of right subtree + 1 */
return max(lheight + rheight + 1, max(ldiameter, rdiameter));
}
// Time Complexity:O(n^2)
// Foldable Binary Tree
// A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable.
bool IsFoldable(struct node *root)
{
if (root == NULL)
{ return true; }
return IsFoldableUtil(root->left, root->right);
}
/* A utility function that checks if trees with roots as n1 and n2
are mirror of each other */
bool IsFoldableUtil(struct node *n1, struct node *n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == NULL && n2 == NULL)
{ return true; }
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == NULL || n2 == NULL)
{ return false; }
/* Otherwise check if left and right subtrees are mirrors of
their counterparts */
return IsFoldableUtil(n1->left, n2->right) && IsFoldableUtil(n1->right, n2->left);
}
// C++ Program to find diagonal
// sum in a Binary Tree
#include <iostream>
#include <stdlib.h>
#include <map>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int data)
{
struct Node* Node =
(struct Node*)malloc(sizeof(struct Node));
Node->data = data;
Node->left = Node->right = NULL;
return Node;
}
// root - root of the binary tree
// vd - vertical distance diagonally
// diagonalSum - map to store Diagonal
// Sum(Passed by Reference)
void diagonalSumUtil(struct Node* root,
int vd, map<int, int> &diagonalSum)
{
if(!root)
return;
diagonalSum[vd] += root->data;
// increase the vertical distance if left child
diagonalSumUtil(root->left, vd + 1, diagonalSum);
// vertical distance remains same for right child
diagonalSumUtil(root->right, vd, diagonalSum);
}
// Function to calculate diagonal
// sum of given binary tree
void diagonalSum(struct Node* root)
{
// create a map to store Diagonal Sum
map<int, int> diagonalSum;
diagonalSumUtil(root, 0, diagonalSum);
map<int, int>::iterator it;
cout << "Diagonal sum in a binary tree is - ";
for(it = diagonalSum.begin();
it != diagonalSum.end(); ++it)
{
cout << it->second << " ";
}
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(9);
root->left->right = newNode(6);
root->right->left = newNode(4);
root->right->right = newNode(5);
root->right->left->right = newNode(7);
root->right->left->left = newNode(12);
root->left->right->left = newNode(11);
root->left->left->right = newNode(10);
diagonalSum(root);
return 0;
}
// A C++ program to find bridges in a given undirected graph
#include<iostream>
#include <list>
#define NIL -1
using namespace std;
// A class that represents an undirected graph
class Graph
{
int V; // No. of vertices
list<int> *adj; // A dynamic array of adjacency lists
void bridgeUtil(int v, bool visited[], int disc[], int low[],
int parent[]);
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // to add an edge to graph
void bridge(); // prints all bridges
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v); // Note: the graph is undirected
}
// A recursive function that finds and prints bridges using
// DFS traversal
// u --> The vertex to be visited next
// visited[] --> keeps tract of visited vertices
// disc[] --> Stores discovery times of visited vertices
// parent[] --> Stores parent vertices in DFS tree
void Graph::bridgeUtil(int u, bool visited[], int disc[],
int low[], int parent[])
{
// A static variable is used for simplicity, we can
// avoid use of static variable by passing a pointer.
static int time = 0;
// Mark the current node as visited
visited[u] = true;
// Initialize discovery time and low value
disc[u] = low[u] = ++time;
// Go through all vertices aadjacent to this
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
{
int v = *i; // v is current adjacent of u
// If v is not visited yet, then recur for it
if (!visited[v])
{
parent[v] = u;
bridgeUtil(v, visited, disc, low, parent);
// Check if the subtree rooted with v has a
// connection to one of the ancestors of u
low[u] = min(low[u], low[v]);
// If the lowest vertex reachable from subtree
// under v is below u in DFS tree, then u-v
// is a bridge
if (low[v] > disc[u])
cout << u <<" " << v << endl;
}
// Update low value of u for parent function calls.
else if (v != parent[u])
low[u] = min(low[u], disc[v]);
}
}
// DFS based function to find all bridges. It uses recursive
// function bridgeUtil()
void Graph::bridge()
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
int *disc = new int[V];
int *low = new int[V];
int *parent = new int[V];
// Initialize parent and visited arrays