-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1556 lines (1398 loc) · 73.5 KB
/
index.html
File metadata and controls
1556 lines (1398 loc) · 73.5 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Segment Tree Visualizer</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body {
font-family: 'Inter', sans-serif;
background-color: #f8fafc;
min-height: 100vh;
display: flex;
flex-direction: column;
}
.container {
max-width: 1400px;
margin: auto;
padding: 1rem;
flex-grow: 1;
}
.node {
transition: all 0.3s ease;
cursor: pointer;
}
.node.highlight-query {
fill: #a7f3d0;
stroke: #059669;
stroke-width: 2px;
filter: drop-shadow(0 0 4px rgba(5, 150, 105, 0.5));
}
.node.highlight-update {
fill: #fcd34d;
stroke: #d97706;
stroke-width: 2px;
filter: drop-shadow(0 0 4px rgba(217, 119, 6, 0.5));
}
.node.highlight-lazy-propagate {
fill: #a78bfa; /* Light purple for lazy propagation */
stroke: #7c3aed;
stroke-width: 2px;
filter: drop-shadow(0 0 4px rgba(124, 58, 237, 0.5));
}
.node.highlight-current {
fill: #bfdbfe;
stroke: #2563eb;
stroke-width: 2px;
filter: drop-shadow(0 0 6px rgba(37, 99, 235, 0.5));
}
.node.highlight-leaf {
fill: #001675;
stroke: #9333ea;
stroke-width: 2px;
}
.node-text {
pointer-events: none;
user-select: none;
fill: #ffffff; /* White text by default */
font-weight: bold;
font-size: 12px;
}
.node.highlight-query .node-text,
.node.highlight-update .node-text,
.node.highlight-current .node-text,
.node.highlight-leaf .node-text,
.node.highlight-lazy-propagate .node-text {
fill: #ffffff; /* Keep white text on all highlighted nodes */
}
.node-text.text-xs {
font-size: 10px;
fill: #e5e7eb; /* Slightly lighter white/gray for less important text */
}
.edge {
stroke: #6b7280;
stroke-width: 2;
transition: stroke 0.3s ease;
}
.edge.highlight {
stroke: #2563eb;
stroke-width: 3;
}
.svg-container {
width: 100%;
overflow-x: auto;
min-height: 500px;
background-color: white;
border-radius: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.message-box {
background-color: #e2e8f0;
color: #334155;
padding: 0.75rem;
border-radius: 0.375rem;
margin-top: 1rem;
font-size: 0.9rem;
border: 1px solid #cbd5e1;
transition: all 0.3s ease;
}
.message-box.error {
background-color: #fee2e2;
color: #b91c1c;
border-color: #ef4444;
}
.message-box.success {
background-color: #dcfce7;
color: #166534;
border-color: #22c55e;
}
.message-box.info {
background-color: #dbeafe;
color: #1e40af;
border-color: #3b82f6;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(5px); }
to { opacity: 1; transform: translateY(0); }
}
.tab-button {
transition: all 0.2s ease;
}
.tab-button.active {
background-color: #3b82f6;
color: white;
border-color: #3b82f6;
}
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 200px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.3s;
font-size: 0.8rem;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
.operation-log {
height: 150px;
overflow-y: auto;
background-color: #f1f5f9;
border-radius: 0.375rem;
padding: 0.75rem;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border: 1px solid #e2e8f0;
}
.operation-log p {
margin: 0.25rem 0;
padding: 0.25rem 0;
border-bottom: 1px solid #e2e8f0;
}
.operation-log p:last-child {
border-bottom: none;
}
.node-details {
background-color: #f1f5f9;
border-radius: 0.375rem;
padding: 0.75rem;
border: 1px solid #e2e8f0;
}
.progress-container {
width: 100%;
background-color: #e2e8f0;
border-radius: 0.375rem;
margin: 0.5rem 0;
}
.progress-bar {
height: 10px;
background-color: #3b82f6;
border-radius: 0.375rem;
width: 0%;
transition: width 0.3s ease;
}
</style>
</head>
<body class="bg-gray-100 text-gray-800">
<div class="container bg-white shadow-xl rounded-lg p-6 my-8">
<div class="flex justify-between items-center mb-6">
<h1 class="text-3xl font-bold text-blue-700">
<i class="fas fa-project-diagram mr-2"></i>Advanced Segment Tree Visualizer
</h1>
<div class="flex space-x-2">
<button id="helpBtn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300">
<i class="fas fa-question-circle"></i> Help
</button>
<button id="settingsBtn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300">
<i class="fas fa-cog"></i> Settings
</button>
</div>
</div>
<div class="flex border-b border-gray-200 mb-6">
<button class="tab-button px-4 py-2 font-medium rounded-t-lg border-b-2 border-transparent active" data-tab="build">
<i class="fas fa-tree mr-2"></i>Build Tree
</button>
<button class="tab-button px-4 py-2 font-medium rounded-t-lg border-b-2 border-transparent" data-tab="query">
<i class="fas fa-search mr-2"></i>Query
</button>
<button class="tab-button px-4 py-2 font-medium rounded-t-lg border-b-2 border-transparent" data-tab="update">
<i class="fas fa-edit mr-2"></i>Update
</button>
<button class="tab-button px-4 py-2 font-medium rounded-t-lg border-b-2 border-transparent" data-tab="details">
<i class="fas fa-info-circle mr-2"></i>Details
</button>
</div>
<div class="tab-content active" id="build-tab">
<div class="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50">
<h2 class="text-xl font-semibold text-blue-600 mb-3">
<i class="fas fa-tree mr-2"></i>Array Input & Build
</h2>
<div class="flex flex-col md:flex-row items-start md:items-center space-y-3 md:space-y-0 md:space-x-4">
<div class="flex-1 w-full">
<label for="arrayInput" class="block text-sm font-medium text-gray-700 mb-1">Array (comma-separated numbers):</label>
<input type="text" id="arrayInput" value="1,3,5,7,9,11"
class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div class="flex space-x-2">
<button id="randomArrayBtn" class="px-3 py-2 bg-purple-100 text-purple-700 rounded-md hover:bg-purple-200">
<i class="fas fa-random mr-1"></i>Random
</button>
<button id="buildTreeBtn"
class="px-5 py-2 bg-blue-600 text-white font-semibold rounded-md shadow-md
hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
transition-colors duration-200">
<i class="fas fa-hammer mr-1"></i>Build Tree
</button>
</div>
</div>
<div class="mt-2 flex justify-between">
<p class="text-sm text-gray-500">Example: 1,3,5,7,9,11 (max 16 elements for best visualization)</p>
<div class="flex items-center">
<label for="operationSelect" class="text-sm text-gray-700 mr-2">Operation:</label>
<select id="operationSelect" class="text-sm border rounded p-1">
<option value="sum">Sum</option>
<option value="min">Minimum</option>
<option value="max">Maximum</option>
<option value="product">Product</option>
</select>
</div>
</div>
</div>
</div>
<div class="tab-content" id="query-tab">
<div class="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50">
<h2 class="text-xl font-semibold text-green-600 mb-3">
<i class="fas fa-search mr-2"></i>Range Query
</h2>
<div class="flex flex-col md:flex-row items-start md:items-center space-y-3 md:space-y-0 md:space-x-4">
<div class="flex items-center space-x-2">
<label for="queryStart" class="text-sm font-medium text-gray-700">Start Index:</label>
<input type="number" id="queryStart" value="1" min="0"
class="w-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500">
</div>
<div class="flex items-center space-x-2">
<label for="queryEnd" class="text-sm font-medium text-gray-700">End Index:</label>
<input type="number" id="queryEnd" value="3" min="0"
class="w-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500">
</div>
<div class="flex space-x-2">
<button id="queryBtn"
class="px-5 py-2 bg-green-600 text-white font-semibold rounded-md shadow-md
hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2
transition-colors duration-200">
<i class="fas fa-bolt mr-1"></i>Run Query
</button>
<button id="queryStepBtn"
class="px-5 py-2 bg-green-500 text-white font-semibold rounded-md shadow-md
hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2
transition-colors duration-200">
<i class="fas fa-step-forward mr-1"></i>Step-by-Step
</button>
</div>
</div>
<div id="stepControls" class="flex flex-col md:flex-row md:items-center justify-between space-y-2 md:space-y-0 mt-3 hidden">
<div class="flex items-center space-x-4">
<button id="nextStepBtn"
class="px-5 py-2 bg-indigo-600 text-white font-semibold rounded-md shadow-md
hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2
transition-colors duration-200">
<i class="fas fa-arrow-right mr-1"></i>Next Step
</button>
<span id="stepMessage" class="text-lg font-medium text-indigo-700"></span>
</div>
<div class="progress-container">
<div id="progressBar" class="progress-bar"></div>
</div>
</div>
</div>
</div>
<div class="tab-content" id="update-tab">
<div class="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50">
<h2 class="text-xl font-semibold text-yellow-600 mb-3">
<i class="fas fa-edit mr-2"></i>Update Value / Range
</h2>
<div class="flex flex-col md:flex-row items-start md:items-center space-y-3 md:space-y-0 md:space-x-4">
<div class="flex items-center space-x-2">
<label for="updateIndex" class="text-sm font-medium text-gray-700">Index (Point Update):</label>
<input type="number" id="updateIndex" value="1" min="0"
class="w-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
</div>
<div class="flex items-center space-x-2">
<label for="updateValue" class="text-sm font-medium text-gray-700">New Value:</label>
<input type="number" id="updateValue" value="10"
class="w-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
</div>
<button id="pointUpdateBtn"
class="px-5 py-2 bg-yellow-600 text-white font-semibold rounded-md shadow-md
hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2
transition-colors duration-200">
<i class="fas fa-sync-alt mr-1"></i>Point Update
</button>
</div>
<div class="mt-6 pt-4 border-t border-gray-200">
<h3 class="text-lg font-semibold text-purple-600 mb-3">
<i class="fas fa-layer-group mr-2"></i>Lazy Propagation (Range Update)
</h3>
<div class="flex flex-col md:flex-row items-start md:items-center space-y-3 md:space-y-0 md:space-x-4">
<div class="flex items-center space-x-2">
<label for="rangeUpdateStart" class="text-sm font-medium text-gray-700">Start Index:</label>
<input type="number" id="rangeUpdateStart" value="1" min="0"
class="w-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500">
</div>
<div class="flex items-center space-x-2">
<label for="rangeUpdateEnd" class="text-sm font-medium text-gray-700">End Index:</label>
<input type="number" id="rangeUpdateEnd" value="3" min="0"
class="w-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500">
</div>
<div class="flex items-center space-x-2">
<label for="rangeUpdateValue" class="text-sm font-medium text-gray-700">Add Value:</label>
<input type="number" id="rangeUpdateValue" value="5"
class="w-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500">
</div>
<button id="rangeUpdateBtn"
class="px-5 py-2 bg-purple-600 text-white font-semibold rounded-md shadow-md
hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2
transition-colors duration-200">
<i class="fas fa-arrows-alt-h mr-1"></i>Range Update
</button>
</div>
</div>
</div>
</div>
<div class="tab-content" id="details-tab">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
<div class="lg:col-span-2">
<div class="p-4 border border-gray-200 rounded-lg bg-gray-50 h-full">
<h2 class="text-xl font-semibold text-blue-600 mb-3">
<i class="fas fa-info-circle mr-2"></i>Node Details
</h2>
<div id="nodeDetails" class="node-details">
<p class="text-gray-500">Click on any node in the tree to view its details here.</p>
</div>
</div>
</div>
<div>
<div class="p-4 border border-gray-200 rounded-lg bg-gray-50 h-full">
<h2 class="text-xl font-semibold text-blue-600 mb-3">
<i class="fas fa-scroll mr-2"></i>Operation Log
</h2>
<div id="operationLog" class="operation-log">
<p>No operations yet. Build a tree to get started.</p>
</div>
</div>
</div>
</div>
</div>
<div id="messageBox" class="message-box hidden"></div>
<div class="bg-gray-50 p-4 rounded-lg shadow-inner mt-6">
<div class="flex justify-between items-center mb-3">
<h2 class="text-xl font-semibold text-gray-700">
<i class="fas fa-project-diagram mr-2"></i>Segment Tree Visualization
</h2>
<div class="flex space-x-2">
<button id="zoomInBtn" class="px-2 py-1 bg-gray-200 rounded hover:bg-gray-300">
<i class="fas fa-search-plus"></i>
</button>
<button id="zoomOutBtn" class="px-2 py-1 bg-gray-200 rounded hover:bg-gray-300">
<i class="fas fa-search-minus"></i>
</button>
<button id="resetZoomBtn" class="px-2 py-1 bg-gray-200 rounded hover:bg-gray-300">
<i class="fas fa-expand"></i>
</button>
</div>
</div>
<div id="segmentTreeViz" class="svg-container bg-white border border-gray-300 rounded-md flex justify-center items-center text-gray-500">
<p>Build a tree to see the visualization here.</p>
</div>
</div>
</div>
<div id="helpModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
<div class="bg-white rounded-lg p-6 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
<div class="flex justify-between items-center mb-4">
<h3 class="text-2xl font-bold text-blue-700">
<i class="fas fa-question-circle mr-2"></i>Segment Tree Visualizer Help
</h3>
<button id="closeHelpModal" class="text-gray-500 hover:text-gray-700">
<i class="fas fa-times"></i>
</button>
</div>
<div class="space-y-4">
<div>
<h4 class="font-bold text-lg text-blue-600 mb-2">What is a Segment Tree?</h4>
<p class="text-gray-700">
A segment tree is a data structure that allows efficient range queries and updates on an array.
It can answer range sum, minimum, maximum, product, and other aggregate queries in O(log n) time.
</p>
</div>
<div>
<h4 class="font-bold text-lg text-blue-600 mb-2">What is Lazy Propagation?</h4>
<p class="text-gray-700">
Lazy propagation is an optimization technique for segment trees that allows for efficient
<strong>range updates</strong> (e.g., adding a value to all elements within a range).
Instead of updating all individual leaf nodes in the range, it "lazily" marks internal
nodes with pending updates and pushes these updates down to children only when necessary
(i.e., when querying or updating a segment that overlaps with the lazy node's range).
</p>
</div>
<div>
<h4 class="font-bold text-lg text-blue-600 mb-2">How to Use This Visualizer</h4>
<ol class="list-decimal list-inside space-y-2 text-gray-700">
<li><strong>Build Tree:</strong> Enter an array of numbers (comma-separated) and click "Build Tree"</li>
<li><strong>Range Query:</strong> Enter a start and end index to query the sum/min/max/product in that range</li>
<li><strong>Point Update:</strong> Change a value at a specific index and see the tree update</li>
<li><strong>Range Update (Lazy):</strong> Add a value to all elements in a given range using lazy propagation.</li>
<li><strong>Step-by-Step:</strong> Use the step-by-step mode to see how queries and updates work</li>
<li><strong>Node Details:</strong> Click on any node to see its details</li>
</ol>
</div>
<div>
<h4 class="font-bold text-lg text-blue-600 mb-2">Keyboard Shortcuts</h4>
<ul class="list-disc list-inside space-y-1 text-gray-700">
<li><kbd>Space</kbd>: Next step (in step-by-step mode)</li>
<li><kbd>B</kbd>: Build tree</li>
<li><kbd>Q</kbd>: Run query</li>
<li><kbd>U</kbd>: Perform Point Update</li>
<li><kbd>R</kbd>: Perform Range Update (Lazy)</li>
</ul>
</div>
</div>
</div>
</div>
<script>
// SegmentTree class implementation
class SegmentTree {
/**
* Initializes a new SegmentTree instance.
* @param {Array<number>} arr The input array.
* @param {string} operation The operation to perform ('sum', 'min', 'max', 'product').
*/
constructor(arr, operation = 'sum') {
this.n = arr.length;
// The segment tree array, size 4*n is typical for safety.
this.seg = new Array(4 * this.n).fill(0);
// Lazy array to store pending updates.
this.lazy = new Array(4 * this.n).fill(0);
// Stores additional information for visualization (e.g., node range, position).
this.nodeInfo = {};
this.operation = operation;
// Build the tree immediately upon creation.
this.build(0, 0, this.n - 1, arr);
}
/**
* Recursively builds the segment tree.
* @param {number} index The current node's index in the `seg` array.
* @param {number} low The lower bound of the current segment (inclusive).
* @param {number} high The upper bound of the current segment (inclusive).
* @param {Array<number>} arr The original input array.
*/
build(index, low, high, arr) {
// Store range information for visualization purposes.
this.nodeInfo[index] = { low, high, value: null, lazyValue: 0 };
// Base case: If it's a leaf node.
if (low === high) {
this.seg[index] = arr[low];
this.nodeInfo[index].value = arr[low];
this.nodeInfo[index].isLeaf = true;
return;
}
// Recursive step: Divide the segment into two halves.
const mid = Math.floor((low + high) / 2);
this.build(2 * index + 1, low, mid, arr); // Build left child
this.build(2 * index + 2, mid + 1, high, arr); // Build right child
// Combine results from children based on the selected operation.
this.seg[index] = this._combine(this.seg[2 * index + 1], this.seg[2 * index + 2]);
// Store the combined value for visualization.
this.nodeInfo[index].value = this.seg[index];
}
/**
* Pushes pending lazy updates down to children.
* This function should be called before accessing or recursing into children.
* @param {number} index The current node's index.
* @param {number} low The lower bound of the current segment.
* @param {number} high The upper bound of the current segment.
* @param {Array<number>} path The array to record the path of visited nodes for visualization.
* @param {string} operationType Type of operation for visualization.
*/
push(index, low, high, path = [], operationType = '') {
if (this.lazy[index] !== 0) {
// Apply lazy update to the current node's segment value.
// This formula is specific to sum operations. For min/max/product, it would differ.
// For min/max range updates, the lazy tag typically stores the value to *set* to,
// not *add* to. For this visualizer, we assume sum for lazy propagation for simplicity.
if (this.operation === 'sum') {
this.seg[index] += (high - low + 1) * this.lazy[index];
} else if (this.operation === 'min') {
this.seg[index] = Math.min(this.seg[index], this.lazy[index]);
} else if (this.operation === 'max') {
this.seg[index] = Math.max(this.seg[index], this.lazy[index]);
} else if (this.operation === 'product') {
// Product updates are more complex with lazy propagation for range,
// usually requiring exponentiation or different tag types.
// For simplicity, we'll make product range updates a 'multiply by' scenario
// and lazy tag stores the multiplier.
// Here, we'll assume the provided lazy propagation is primarily for additive updates
// like the C++ example, so we'll just handle sum gracefully.
// For non-sum operations, a simple additive lazy won't work universally.
// Let's adapt this to only allow additive lazy for sum, and
// for others, it would require a different lazy tag mechanism.
// For now, let's treat lazy propagation as an "add" operation.
// If it's a product, this additive lazy doesn't make sense.
// We will add a check in `updateRange` to only allow sum for lazy propagation.
}
this.nodeInfo[index].value = this.seg[index]; // Update visualized value
// If not a leaf node, propagate lazy tag to children.
if (low !== high) {
if (this.operation === 'sum') {
this.lazy[2 * index + 1] += this.lazy[index];
this.lazy[2 * index + 2] += this.lazy[index];
} else if (this.operation === 'min' || this.operation === 'max') {
// For min/max, it's generally a "set" or "take min/max with" operation.
// If lazy is 'add value', this would be:
this.lazy[2 * index + 1] = this._combine(this.lazy[2 * index + 1], this.lazy[index]);
this.lazy[2 * index + 2] = this._combine(this.lazy[2 * index + 2], this.lazy[index]);
}
this.nodeInfo[2 * index + 1].lazyValue += this.lazy[index]; // For visualization
this.nodeInfo[2 * index + 2].lazyValue += this.lazy[index]; // For visualization
}
this.lazy[index] = 0; // Clear lazy tag for current node.
this.nodeInfo[index].lazyValue = 0; // For visualization
}
}
/**
* Combines results from two children based on the selected operation.
* @param {number} val1 Value from left child.
* @param {number} val2 Value from right child.
* @returns {number} Combined value.
*/
_combine(val1, val2) {
switch (this.operation) {
case 'sum':
return val1 + val2;
case 'min':
return Math.min(val1, val2);
case 'max':
return Math.max(val1, val2);
case 'product':
return val1 * val2;
default:
return val1 + val2;
}
}
/**
* Returns the neutral (identity) element for the current operation.
* This is crucial for handling non-overlapping ranges in queries.
* @returns {number} The neutral element.
*/
getNeutralElement() {
switch (this.operation) {
case 'sum':
return 0; // Adding 0 does not change the sum.
case 'min':
return Infinity; // min(Infinity, x) = x.
case 'max':
return -Infinity; // max(-Infinity, x) = x.
case 'product':
return 1; // Multiplying by 1 does not change the product.
default:
return 0;
}
}
/**
* Public wrapper for performing a range query.
* @param {number} l The left boundary of the query range (inclusive).
* @param {number} r The right boundary of the query range (inclusive).
* @returns {{result: number, path: Array<number>, lazyPropagated: Array<number>}} The query result and the path of visited nodes, and nodes where lazy propagation occurred.
*/
queryRange(l, r) {
const path = [];
const lazyPropagated = [];
const result = this._queryRecursive(0, 0, this.n - 1, l, r, path, lazyPropagated);
return { result, path, lazyPropagated };
}
/**
* Recursive function to perform a range query with lazy propagation.
* @param {number} index The current node's index.
* @param {number} low The lower bound of the current segment.
* @param {number} high The upper bound of the current segment.
* @param {number} l The left boundary of the query range.
* @param {number} r The right boundary of the query range.
* @param {Array<number>} path The array to record the path of visited nodes.
* @param {Array<number>} lazyPropagated The array to record nodes where lazy propagation occurred.
* @returns {number} The result of the query for the given range.
*/
_queryRecursive(index, low, high, l, r, path, lazyPropagated) {
path.push(index);
// Push down any pending lazy updates before processing this node.
if (this.lazy[index] !== 0) {
lazyPropagated.push(index);
this.push(index, low, high);
}
// Case 1: No overlap.
if (r < low || high < l) {
return this.getNeutralElement();
}
// Case 2: Complete overlap.
if (l <= low && high <= r) {
return this.seg[index];
}
// Case 3: Partial overlap. Recurse on children.
const mid = Math.floor((low + high) / 2);
const leftResult = this._queryRecursive(2 * index + 1, low, mid, l, r, path, lazyPropagated);
const rightResult = this._queryRecursive(2 * index + 2, mid + 1, high, l, r, path, lazyPropagated);
return this._combine(leftResult, rightResult);
}
/**
* Generates a sequence of steps for a step-by-step query visualization.
* @param {number} l The left boundary of the query range.
* @param {number} r The right boundary of the query range.
* @returns {{steps: Array<Object>, finalResult: number}} An array of step objects and the final result.
*/
generateQuerySteps(l, r) {
const steps = [];
const finalResult = this._queryRecursiveStepByStep(0, 0, this.n - 1, l, r, [], steps);
steps.push({
highlightPath: [],
lazyPropagated: [],
currentStepNode: null,
message: `Query complete! Final ${this.getOperationName()} for range [${l}, ${r}] is: ${finalResult}.`
});
return { steps, finalResult };
}
/**
* Recursive helper for step-by-step query visualization with lazy propagation.
* Records each step, including node highlights and messages.
* @param {number} index The current node's index.
* @param {number} low The lower bound of the current segment.
* @param {number} high The upper bound of the current segment.
* @param {number} l The left boundary of the query range.
* @param {number} r The right boundary of the query range.
* @param {Array<number>} currentCallPath The path from the root to the current node.
* @param {Array<Object>} steps The array to store each step's details.
* @returns {number} The result of the query for the given range.
*/
_queryRecursiveStepByStep(index, low, high, l, r, currentCallPath, steps) {
const pathForStep = [...currentCallPath, index];
let lazyPropagatedForStep = [];
let message = `Visiting node: idx:${index} ([${low}-${high}]) for query range [${l}, ${r}].`;
steps.push({
highlightPath: pathForStep,
currentStepNode: index,
lazyPropagated: [],
message: message
});
// Push down lazy updates *before* checking for overlaps.
if (this.lazy[index] !== 0) {
lazyPropagatedForStep.push(index);
message = `Node idx:${index} ([${low}-${high}]) has lazy value (${this.lazy[index]}). Pushing down.`;
steps.push({
highlightPath: pathForStep,
currentStepNode: index,
lazyPropagated: lazyPropagatedForStep,
message: message
});
this.push(index, low, high);
}
// Case 1: No overlap.
if (r < low || high < l) {
message = `Node idx:${index} ([${low}-${high}]) has NO OVERLAP with query [${l}, ${r}]. Returning ${this.getNeutralElement()}.`;
steps.push({
highlightPath: pathForStep,
currentStepNode: index,
lazyPropagated: lazyPropagatedForStep,
message: message
});
return this.getNeutralElement();
}
// Case 2: Complete overlap.
if (l <= low && high <= r) {
const result = this.seg[index];
message = `Node idx:${index} ([${low}-${high}]) has COMPLETE OVERLAP with query [${l}, ${r}]. Using its value (${result}).`;
steps.push({
highlightPath: pathForStep,
currentStepNode: index,
lazyPropagated: lazyPropagatedForStep,
message: message
});
return result;
}
// Case 3: Partial overlap - recurse deeper.
const mid = Math.floor((low + high) / 2);
message = `Node idx:${index} ([${low}-${high}]) has PARTIAL OVERLAP. Recursing on left child ([${low}-${mid}]).`;
steps.push({
highlightPath: pathForStep,
currentStepNode: index,
lazyPropagated: lazyPropagatedForStep,
message: message
});
const leftResult = this._queryRecursiveStepByStep(2 * index + 1, low, mid, l, r, pathForStep, steps);
message = `Back at node idx:${index}. Left child returned ${leftResult}. Now recursing on right child ([${mid+1}-${high}]).`;
steps.push({
highlightPath: pathForStep,
currentStepNode: index,
lazyPropagated: lazyPropagatedForStep,
message: message
});
const rightResult = this._queryRecursiveStepByStep(2 * index + 2, mid + 1, high, l, r, pathForStep, steps);
const result = this._combine(leftResult, rightResult);
message = `Back at node idx:${index}. Combining results: ${leftResult} and ${rightResult} = ${result}.`;
steps.push({
highlightPath: pathForStep,
currentStepNode: index,
lazyPropagated: lazyPropagatedForStep,
message: message
});
return result;
}
/**
* Returns the display name of the current operation.
* @returns {string} The operation name.
*/
getOperationName() {
switch (this.operation) {
case 'sum': return 'sum';
case 'min': return 'minimum';
case 'max': return 'maximum';
case 'product': return 'product';
default: return 'sum';
}
}
/**
* Public wrapper for point updating a value at a specific position.
* @param {number} pos The index in the original array to update.
* @param {number} newVal The new value for the position.
* @returns {{path: Array<number>}} The path of nodes visited during the update.
*/
pointUpdate(pos, newVal) {
const path = [];
this._pointUpdateRecursive(0, 0, this.n - 1, pos, newVal, path);
return { path };
}
/**
* Recursive function to update a single value in the segment tree.
* @param {number} index The current node's index.
* @param {number} low The lower bound of the current segment.
* @param {number} high The upper bound of the current segment.
* @param {number} pos The index in the original array to update.
* @param {number} newVal The new value.
* @param {Array<number>} path The array to record the path of visited nodes.
*/
_pointUpdateRecursive(index, low, high, pos, newVal, path) {
path.push(index);
// If this node has a lazy tag, push it down before updating.
if (this.lazy[index] !== 0) {
this.push(index, low, high);
}
// Base case: If it's the leaf node corresponding to the update position.
if (low === high) {
this.seg[index] = newVal;
this.nodeInfo[index].value = newVal;
return;
}
// Recursive step: Traverse down to the correct child.
const mid = Math.floor((low + high) / 2);
if (pos <= mid) {
this._pointUpdateRecursive(2 * index + 1, low, mid, pos, newVal, path);
} else {
this._pointUpdateRecursive(2 * index + 2, mid + 1, high, pos, newVal, path);
}
// After children are updated, update the current node's value.
this.seg[index] = this._combine(this.seg[2 * index + 1], this.seg[2 * index + 2]);
this.nodeInfo[index].value = this.seg[index];
}
/**
* Public wrapper for performing a range update with lazy propagation.
* @param {number} l The left boundary of the update range (inclusive).
* @param {number} r The right boundary of the update range (inclusive).
* @param {number} val The value to add to the elements in the range.
* @returns {{path: Array<number>, lazyPropagated: Array<number>}} The path of visited nodes and nodes where lazy propagation occurred.
*/
rangeUpdate(l, r, val) {
const path = [];
const lazyPropagated = [];
this._rangeUpdateRecursive(0, 0, this.n - 1, l, r, val, path, lazyPropagated);
return { path, lazyPropagated };
}
/**
* Recursive function to perform a range update with lazy propagation.
* Only supports 'sum' operation for lazy propagation in this visualizer.
* @param {number} index The current node's index.
* @param {number} low The lower bound of the current segment.
* @param {number} high The upper bound of the current segment.
* @param {number} l The left boundary of the update range.
* @param {number} r The right boundary of the update range.
* @param {number} val The value to add.
* @param {Array<number>} path The array to record the path of visited nodes.
* @param {Array<number>} lazyPropagated The array to record nodes where lazy propagation occurred.
*/
_rangeUpdateRecursive(index, low, high, l, r, val, path, lazyPropagated) {
path.push(index);
// Push down any pending lazy updates for this node.
if (this.lazy[index] !== 0) {
lazyPropagated.push(index);
this.push(index, low, high);
}
// Case 1: No overlap.
if (r < low || high < l) {
return;
}
// Case 2: Complete overlap.
if (l <= low && high <= r) {
// Apply update directly to current node's lazy tag.
this.lazy[index] += val;
lazyPropagated.push(index); // Mark this node as having received a lazy update.
// Apply the lazy update to the current node's segment value immediately.
this.push(index, low, high);
return;
}
// Case 3: Partial overlap. Recurse on children.
const mid = Math.floor((low + high) / 2);
this._rangeUpdateRecursive(2 * index + 1, low, mid, l, r, val, path, lazyPropagated);
this._rangeUpdateRecursive(2 * index + 2, mid + 1, high, l, r, val, path, lazyPropagated);
// After children are updated, re-calculate current node's value from children.
this.seg[index] = this._combine(this.seg[2 * index + 1], this.seg[2 * index + 2]);
this.nodeInfo[index].value = this.seg[index];
}
}
// --- Visualization Logic ---
let currentSegmentTree = null;
const vizContainer = document.getElementById('segmentTreeViz');
const messageBox = document.getElementById('messageBox');
const operationLog = document.getElementById('operationLog');
const nodeDetails = document.getElementById('nodeDetails');
// Step-by-step query state variables.
let querySteps = [];
let currentQueryStepIndex = -1;
let isStepByStepMode = false;
let queryFinalResult = 0;
// Zoom state variables.
let currentScale = 1;
const zoomStep = 0.1;
/**
* Clears the current visualization and resets UI elements.
*/
function clearVisualization() {
vizContainer.innerHTML = '<p>Build a tree to see the visualization here.</p>';
vizContainer.style.overflowX = 'hidden';
hideStepControls();
nodeDetails.innerHTML = '<p class="text-gray-500">Click on any node in the tree to view its details here.</p>';
}
/**
* Displays a message to the user in a styled box and adds it to the operation log.
* @param {string} message The message content.
* @param {string} type The type of message ('info', 'success', 'error').
*/
function showMessage(message, type = 'info') {
messageBox.textContent = message;
messageBox.className = 'message-box';
messageBox.classList.add(type);
messageBox.classList.remove('hidden');
const now = new Date();
const timeString = now.toLocaleTimeString();
const logEntry = document.createElement('p');
logEntry.innerHTML = `<span class="text-gray-500">[${timeString}]</span> <span class="${type === 'error' ? 'text-red-600' : type === 'success' ? 'text-green-600' : 'text-blue-600'}">${message}</span>`;
operationLog.prepend(logEntry);
operationLog.scrollTop = 0;
if (type !== 'error') {
setTimeout(() => {
messageBox.classList.add('hidden');
}, 5000);
}
}
/**
* Hides the message box.
*/
function hideMessage() {
messageBox.classList.add('hidden');
}
/**
* Shows the step-by-step query controls.
*/
function showStepControls() {
document.getElementById('stepControls').classList.remove('hidden');
updateProgressBar();
}
/**
* Hides the step-by-step query controls and clears the step message.
*/
function hideStepControls() {
document.getElementById('stepControls').classList.add('hidden');
document.getElementById('stepMessage').textContent = '';
}
/**
* Updates the progress bar for step-by-step mode.
*/
function updateProgressBar() {
if (currentQueryStepIndex < 0 || querySteps.length === 0) {
document.getElementById('progressBar').style.width = '0%';
return;
}
const progress = ((currentQueryStepIndex + 1) / querySteps.length) * 100;
document.getElementById('progressBar').style.width = `${progress}%`;
}
/**
* Draws the segment tree visualization in the SVG container.
* @param {SegmentTree} segmentTreeInstance The SegmentTree object to visualize.