SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Advanced Search Techniques


Md. Shakil Ahmed.
Topic
• Binary search
• Bisection
• Ternary Search
Binary search algorithm
• binary search or half-interval search finds the position
  of a specified value within a sorted array.
• In each step, the algorithm compares the input key
  value with the key value of the middle element of the
  array.
• If the keys match, then a matching element has been
  found so its index, or position, is returned.
• Otherwise, if the sought key is less than the middle
  element's key, then the algorithm repeats its action on
  the sub-array to the left of the middle element or, if
  the input key is greater, on the sub-array to the right.
• If the remaining array to be searched is reduced to
  zero, then the key cannot be found in the array and a
  special "Not found" indication is returned.
Iterative
int binary_search(int A[], int key, int imin, int imax)
{
while (imax >= imin) {
int imid = (imin + imax) / 2;
if (A[imid] < key)
imin = imid + 1;
else if (A[imid] > key )
imax = imid - 1;
else return imid;
}
return KEY_NOT_FOUND;
}
Recursive
int binary_search(int A[], int key, int imin, int imax)
   {
if (imax < imin) return KEY_NOT_FOUND;
else {
int imid = (imin + imax) / 2;
if (A[imid] > key)
return binary_search(A, key, imin, imid-1);
else if (A[imid] < key)
return binary_search(A, key, imid+1, imax);
Else
return imid;
}}
Performance
• The worst case is Log2(N).
1088 - Points in Segments
• Given n points (1 dimensional) and q
  segments, you have to find the number of
  points that lie in each of the segments. A point
  pi will lie in a segment A B if A ≤ pi ≤ B.
• For example if the points are 1, 4, 6, 8, 10.
  And the segment is 0 to 5. Then there are 2
  points that lie in the segment.
Input
• input starts with an integer T (≤ 5), denoting the
  number of test cases.
• Each case starts with a line containing two
  integers n (1 ≤ n ≤ 105) and q (1 ≤ q ≤ 50000). The
  next line contains n space separated integers
  denoting the points in ascending order. All the
  integers are distinct and each of them range in
  [0, 108].
• Each of the next q lines contains two integers Ak
  Bk (0 ≤ Ak ≤ Bk ≤ 108) denoting a segment.
Output
• For each case, print the case number in a
  single line. Then for each segment, print the
  number of points that lie in that segment.
Solution
int binary_search (int key)
{
 int start, end,middle;
                                 while(middle+1<=n && A[middle+1]<= key)
start = 0;                       middle++;
end = n;
middle = (start+ end)/2;         while(middle-1>=0 && A[middle-1]> key)
                                 middle--;
while(start<= end)
{                                 return middle;
if(Array[middle]== key)          }
break;
else if(A[middle]> key)
end = middle - 1;
else
start = middle + 1;

middle = (start+ end)/2;
}
Solution
scanf("%d %d",&n,&q);

A[0]=-1000;
for(i=1;i<=n;i++)
scanf("%d",&A[i]);

for(q1=1;q1<=q;q1++)
{
scanf("%d %d",&x,&y);
printf("%dn", binary_search(y)- binary_search(x-1));

}
1043 - Triangle Partitioning




• You are given AB, AC and BC. DE is parallel to
  BC. You are also given the area ratio between
  ADE and BDEC. You have to find the value of
  AD.
Input
• Input starts with an integer T (≤ 25), denoting the
  number of test cases.
• Each case begins with four real numbers
  denoting AB, AC, BC and the ratio of ADE and
  BDEC (ADE / BDEC). You can safely assume that
  the given triangle is a valid triangle with positive
  area.
                       Output
For each case of input you have to print the case
number and AD. Errors less than 10-6 will be ignored.
Solution
double Area(double x1, double y1, double z1)
{
  double s = (x1 + y1 + z1)/2;
  return sqrtl(s * (s-x1) * (s-y1) * (s-z1));
}

scanf("%lf %lf %lf %lf",&ab,&ac,&bc,&ratio);

area = Area(ab,ac,bc);
start = 0;
end = ab;
previous = -100;
middle = (start+end)/2;
Solution
while(start<=end)
                             previous = middle - previous;
{
                             if(previous<0)
ab1 = middle;
                             previous = - previous;
ac1 = (ac * middle)/ab;
bc1 = (bc * middle)/ab;
                             if(previous<0.000001)
                             break;
area1 = Area(ab1,ac1,bc1);
area2 = area - area1;        previous = middle;
                             }
if(area1/area2>= ratio)
                             printf("Case %d: %lfn",caseNumber,middle);
end = middle;
else
start = middle;

middle = (start+end)/2;
Similar
•   1048 - Conquering Keokradong
•   1056 - Olympics
•   1076 - Get the Containers
•   1138 - Trailing Zeroes (III)
•   1276 - Very Lucky Numbers
Bisection
• Bisection -> two section
• Divide elements to 2 part.
• Then sort one part & use binary search.
1127 - Funny Knapsack
• Given n integers and a knapsack of weight W, you have to
  count the number of combinations for which you can add
  the items in the knapsack without overflowing the weight.
• Input
• Input starts with an integer T (≤ 100), denoting the number
  of test cases.
• Each case contains two integers n (1 ≤ n ≤ 30) and W (1 ≤ W
  ≤ 2 * 109) and the next line will contain n integers separated
  by spaces. The integers will be non negative and less than
  109.
• Output
• For each set of input, print the case number and the
  number of possible combinations.
Solution
scanf("%d %d",&n,&k);

   for(i=0;i<n;i++)           for(i=m;i<n;i++)
   scanf("%lld",&X[i]);       {
                              N3=N2;
   m = n/2;
                              for(j=0;j<N2;j++)
   A[0]=0;                    {
   N1=1;                      B[N3]=B[j]+X[i];
   B[0]=0;                    N3++;
   N2=1;                      }
   for(i=0;i<m;i++)           N2=N3;
   {                          }
   N3=N1;
   for(j=0;j<N1;j++)          sort(B,B+N2);
   {
   A[N3]=A[j]+X[i];
   N3++;
   }
   N1=N3;
   }
Solution
total = 0;                      while(B[mid]>t)
                                    mid--;
   for(i=0;i<N1;i++)
   if(k>=A[i])
   {                                  while(mid+1<N2 && B[mid+1]<=t)
     t = k-A[i];                      mid++;
     int left = 0;
     int right = N2 - 1;              total += (mid+1);
     mid = (left+right)/2;        }
     while(left<=right)
     {                            printf("Case %d: %dn",caseNumber,total);
       if(B[mid]==t)
       break;
       else if(B[mid]>t)
       right=mid-1;
       else
       left = mid+1;
       mid = (left+right)/2;
     }
Similar
• 1235 - Coin Change (IV)
Ternary Search
• A ternary search algorithm is a technique for
  finding the minimum or maximum of a
  unimodal function.
Recursive algorithm
def ternarySearch(f, left, right, absolutePrecision):
if (right - left) < absolutePrecision:
return (left + right)/2
leftThird = (2*left + right)/3
rightThird = (left + 2*right)/3
if f(leftThird) < f(rightThird):
return ternarySearch(f, leftThird, right, absolutePrecision)
else:
return ternarySearch(f, left, rightThird, absolutePrecision)
1146 - Closest Distance
• Two men are moving concurrently, one man is
  moving from A to B and other man is moving
  from C to D. Initially the first man is at A, and
  the second man is at C. They maintain
  constant velocities such that when the first
  man reaches B, at the same time the second
  man reaches D. You can assume that A, B, C
  and D are 2D Cartesian co-ordinates. You have
  to find the minimum Euclidean distance
  between them along their path.
• Input
• Input starts with an integer T (≤ 1000), denoting the
  number of test cases.
• Each case will contain eight integers: Ax, Ay, Bx, By, Cx, Cy,
  Dx, Dy. All the co-ordinates are between 0 and 100. (Ax,
  Ay) denotes A. (Bx, By) denotes B and so on.
• Output
• For each case, print the case number and the minimum
  distance between them along their path. Errors less
  than 10-6 will be ignored.
Solution
void makePoint(double h1, double h2)
{
double h3 = (ax - h1)*(ax - h1) + (ay - h2) * (ay - h2);
h3 = sqrt(h3);

double h4 = dis - h3;

mx = (cx * h4 + dx * h3)/dis;
my = (cy * h4 + dy * h3)/dis;
}

double distance(double h1, double h2, double h3, double h4)
{
double h5 = (h1-h3)*(h1-h3) + (h2-h4)*(h2-h4);
return sqrt(h5);
}
Solution
dis = (ax - bx)*(ax - bx) + (ay - by) * (ay - by);
dis = sqrt(dis);

min = (ax - cx)*(ax - cx) + (ay - cy) * (ay - cy);
min = sqrt(min);

leftx = ax;
lefty = ay;
rightx = bx;
righty = by;

while(1)
{
                                                 rightThirdx = (leftx + 2*rightx)/3;
leftThirdx = (2*leftx + rightx)/3;               rightThirdy = (lefty + 2*righty)/3;
leftThirdy = (2*lefty + righty)/3;               makePoint(rightThirdx,rightThirdy);
makePoint(leftThirdx,leftThirdy);                disRight =
disLeft = distance(leftThirdx,leftThirdy,mx,my); distance(rightThirdx,rightThirdy,mx,my);
Solution
if(disLeft<=disRight)        min2 = min - min1;
 {                           if(min2<0)
                             min2=-min2;
    rightx = rightThirdx;
                             if(min2<0.0000000001)
    righty = rightThirdy;    break;
    min1 = disLeft;          min = min1;
 }                          }
 else
                            printf("Case %ld: %lfn",cas1,min);
 {
    leftx = leftThirdx;
    lefty = leftThirdy;
    min1 = disRight;
 }
Similar
• 1240 - Point Segment Distance (3D)
Thanks

Weitere ähnliche Inhalte

Was ist angesagt?

C2 st lecture 5 handout
C2 st lecture 5 handoutC2 st lecture 5 handout
C2 st lecture 5 handout
fatima d
 
C2 st lecture 6 handout
C2 st lecture 6 handoutC2 st lecture 6 handout
C2 st lecture 6 handout
fatima d
 
Image Cryptography and Steganography
Image Cryptography and SteganographyImage Cryptography and Steganography
Image Cryptography and Steganography
Mohammad Amin Amjadi
 
Math lecture 7 (Arithmetic Sequence)
Math lecture 7 (Arithmetic Sequence)Math lecture 7 (Arithmetic Sequence)
Math lecture 7 (Arithmetic Sequence)
Osama Zahid
 

Was ist angesagt? (15)

C2 st lecture 5 handout
C2 st lecture 5 handoutC2 st lecture 5 handout
C2 st lecture 5 handout
 
Path relinking for high dimensional continuous optimization
Path relinking for high dimensional continuous optimizationPath relinking for high dimensional continuous optimization
Path relinking for high dimensional continuous optimization
 
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGAScientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
 
ArproTree_journal
ArproTree_journalArproTree_journal
ArproTree_journal
 
C2 st lecture 6 handout
C2 st lecture 6 handoutC2 st lecture 6 handout
C2 st lecture 6 handout
 
Top school in delhi ncr
Top school in delhi ncrTop school in delhi ncr
Top school in delhi ncr
 
ゲーム理論NEXT 線形計画問題第5回 -双対定理証明-
ゲーム理論NEXT 線形計画問題第5回 -双対定理証明-ゲーム理論NEXT 線形計画問題第5回 -双対定理証明-
ゲーム理論NEXT 線形計画問題第5回 -双対定理証明-
 
Image Cryptography and Steganography
Image Cryptography and SteganographyImage Cryptography and Steganography
Image Cryptography and Steganography
 
Quadratic equations
Quadratic equationsQuadratic equations
Quadratic equations
 
Tail Probabilities for Randomized Program Runtimes via Martingales for Higher...
Tail Probabilities for Randomized Program Runtimes via Martingales for Higher...Tail Probabilities for Randomized Program Runtimes via Martingales for Higher...
Tail Probabilities for Randomized Program Runtimes via Martingales for Higher...
 
Math lecture 7 (Arithmetic Sequence)
Math lecture 7 (Arithmetic Sequence)Math lecture 7 (Arithmetic Sequence)
Math lecture 7 (Arithmetic Sequence)
 
8. Hash table
8. Hash table8. Hash table
8. Hash table
 
CMSC 56 | Lecture 8: Growth of Functions
CMSC 56 | Lecture 8: Growth of FunctionsCMSC 56 | Lecture 8: Growth of Functions
CMSC 56 | Lecture 8: Growth of Functions
 
Ep 5512 lecture-02
Ep 5512 lecture-02Ep 5512 lecture-02
Ep 5512 lecture-02
 
Rosser's theorem
Rosser's theoremRosser's theorem
Rosser's theorem
 

Andere mochten auch

11 x1 t14 06 sum of a geometric series (2012)
11 x1 t14 06 sum of a geometric series (2012)11 x1 t14 06 sum of a geometric series (2012)
11 x1 t14 06 sum of a geometric series (2012)
Nigel Simmons
 
13 3 arithmetic and geometric series and their sums
13 3 arithmetic and geometric series and their sums13 3 arithmetic and geometric series and their sums
13 3 arithmetic and geometric series and their sums
hisema01
 
Problem solving on acm international collegiate programming contest
Problem solving on acm international collegiate programming contestProblem solving on acm international collegiate programming contest
Problem solving on acm international collegiate programming contest
Fedor Tsarev
 
From Competition to Complementarity: Comparative Influence Diffusion and Maxi...
From Competition to Complementarity: Comparative Influence Diffusion and Maxi...From Competition to Complementarity: Comparative Influence Diffusion and Maxi...
From Competition to Complementarity: Comparative Influence Diffusion and Maxi...
Wei Lu
 
A Novel Target Marketing Approach based on Influence Maximization
A Novel Target Marketing Approach based on Influence MaximizationA Novel Target Marketing Approach based on Influence Maximization
A Novel Target Marketing Approach based on Influence Maximization
Surendra Gadwal
 
IMAX PRESENTATION
IMAX PRESENTATIONIMAX PRESENTATION
IMAX PRESENTATION
Sebby23
 

Andere mochten auch (14)

11 x1 t14 06 sum of a geometric series (2012)
11 x1 t14 06 sum of a geometric series (2012)11 x1 t14 06 sum of a geometric series (2012)
11 x1 t14 06 sum of a geometric series (2012)
 
13 3 arithmetic and geometric series and their sums
13 3 arithmetic and geometric series and their sums13 3 arithmetic and geometric series and their sums
13 3 arithmetic and geometric series and their sums
 
Problem solving on acm international collegiate programming contest
Problem solving on acm international collegiate programming contestProblem solving on acm international collegiate programming contest
Problem solving on acm international collegiate programming contest
 
05 динамическое программирование
05 динамическое программирование05 динамическое программирование
05 динамическое программирование
 
From Competition to Complementarity: Comparative Influence Diffusion and Maxi...
From Competition to Complementarity: Comparative Influence Diffusion and Maxi...From Competition to Complementarity: Comparative Influence Diffusion and Maxi...
From Competition to Complementarity: Comparative Influence Diffusion and Maxi...
 
A Novel Target Marketing Approach based on Influence Maximization
A Novel Target Marketing Approach based on Influence MaximizationA Novel Target Marketing Approach based on Influence Maximization
A Novel Target Marketing Approach based on Influence Maximization
 
Scalable and Parallelizable Processing of Influence Maximization for Large-S...
Scalable and Parallelizable Processing of Influence Maximization  for Large-S...Scalable and Parallelizable Processing of Influence Maximization  for Large-S...
Scalable and Parallelizable Processing of Influence Maximization for Large-S...
 
Aslay Ph.D. Defense
Aslay Ph.D. DefenseAslay Ph.D. Defense
Aslay Ph.D. Defense
 
Unit v computer, number system
Unit  v computer, number systemUnit  v computer, number system
Unit v computer, number system
 
Geometric series
Geometric seriesGeometric series
Geometric series
 
Bisection
BisectionBisection
Bisection
 
Arithmetic Sequence and Arithmetic Series
Arithmetic Sequence and Arithmetic SeriesArithmetic Sequence and Arithmetic Series
Arithmetic Sequence and Arithmetic Series
 
IMAX PRESENTATION
IMAX PRESENTATIONIMAX PRESENTATION
IMAX PRESENTATION
 
ACM ICPC 2014 NEERC (Northeastern European Regional Contest) Problems Review
ACM ICPC 2014 NEERC (Northeastern European Regional Contest) Problems ReviewACM ICPC 2014 NEERC (Northeastern European Regional Contest) Problems Review
ACM ICPC 2014 NEERC (Northeastern European Regional Contest) Problems Review
 

Ähnlich wie Advanced Search Techniques

Open GL T0074 56 sm4
Open GL T0074 56 sm4Open GL T0074 56 sm4
Open GL T0074 56 sm4
Roziq Bahtiar
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
kesav24
 
Matrix 2 d
Matrix 2 dMatrix 2 d
Matrix 2 d
xyz120
 

Ähnlich wie Advanced Search Techniques (20)

Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Matlab assignment
Matlab assignmentMatlab assignment
Matlab assignment
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
 
Cs580
Cs580Cs580
Cs580
 
2. Fixed Point Iteration.pptx
2. Fixed Point Iteration.pptx2. Fixed Point Iteration.pptx
2. Fixed Point Iteration.pptx
 
Matlab file
Matlab file Matlab file
Matlab file
 
Recursion
RecursionRecursion
Recursion
 
Lecture5
Lecture5Lecture5
Lecture5
 
Open GL T0074 56 sm4
Open GL T0074 56 sm4Open GL T0074 56 sm4
Open GL T0074 56 sm4
 
Matlab lab manual
Matlab lab manualMatlab lab manual
Matlab lab manual
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
Matrix 2 d
Matrix 2 dMatrix 2 d
Matrix 2 d
 
10 linescan
10 linescan10 linescan
10 linescan
 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdf
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And Analysis
 
kactl.pdf
kactl.pdfkactl.pdf
kactl.pdf
 

Mehr von Shakil Ahmed (20)

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

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Kürzlich hochgeladen (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

Advanced Search Techniques

  • 2. Topic • Binary search • Bisection • Ternary Search
  • 3. Binary search algorithm • binary search or half-interval search finds the position of a specified value within a sorted array. • In each step, the algorithm compares the input key value with the key value of the middle element of the array. • If the keys match, then a matching element has been found so its index, or position, is returned. • Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. • If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned.
  • 4. Iterative int binary_search(int A[], int key, int imin, int imax) { while (imax >= imin) { int imid = (imin + imax) / 2; if (A[imid] < key) imin = imid + 1; else if (A[imid] > key ) imax = imid - 1; else return imid; } return KEY_NOT_FOUND; }
  • 5. Recursive int binary_search(int A[], int key, int imin, int imax) { if (imax < imin) return KEY_NOT_FOUND; else { int imid = (imin + imax) / 2; if (A[imid] > key) return binary_search(A, key, imin, imid-1); else if (A[imid] < key) return binary_search(A, key, imid+1, imax); Else return imid; }}
  • 6. Performance • The worst case is Log2(N).
  • 7. 1088 - Points in Segments • Given n points (1 dimensional) and q segments, you have to find the number of points that lie in each of the segments. A point pi will lie in a segment A B if A ≤ pi ≤ B. • For example if the points are 1, 4, 6, 8, 10. And the segment is 0 to 5. Then there are 2 points that lie in the segment.
  • 8. Input • input starts with an integer T (≤ 5), denoting the number of test cases. • Each case starts with a line containing two integers n (1 ≤ n ≤ 105) and q (1 ≤ q ≤ 50000). The next line contains n space separated integers denoting the points in ascending order. All the integers are distinct and each of them range in [0, 108]. • Each of the next q lines contains two integers Ak Bk (0 ≤ Ak ≤ Bk ≤ 108) denoting a segment.
  • 9. Output • For each case, print the case number in a single line. Then for each segment, print the number of points that lie in that segment.
  • 10. Solution int binary_search (int key) { int start, end,middle; while(middle+1<=n && A[middle+1]<= key) start = 0; middle++; end = n; middle = (start+ end)/2; while(middle-1>=0 && A[middle-1]> key) middle--; while(start<= end) { return middle; if(Array[middle]== key) } break; else if(A[middle]> key) end = middle - 1; else start = middle + 1; middle = (start+ end)/2; }
  • 12. 1043 - Triangle Partitioning • You are given AB, AC and BC. DE is parallel to BC. You are also given the area ratio between ADE and BDEC. You have to find the value of AD.
  • 13. Input • Input starts with an integer T (≤ 25), denoting the number of test cases. • Each case begins with four real numbers denoting AB, AC, BC and the ratio of ADE and BDEC (ADE / BDEC). You can safely assume that the given triangle is a valid triangle with positive area. Output For each case of input you have to print the case number and AD. Errors less than 10-6 will be ignored.
  • 14. Solution double Area(double x1, double y1, double z1) { double s = (x1 + y1 + z1)/2; return sqrtl(s * (s-x1) * (s-y1) * (s-z1)); } scanf("%lf %lf %lf %lf",&ab,&ac,&bc,&ratio); area = Area(ab,ac,bc); start = 0; end = ab; previous = -100; middle = (start+end)/2;
  • 15. Solution while(start<=end) previous = middle - previous; { if(previous<0) ab1 = middle; previous = - previous; ac1 = (ac * middle)/ab; bc1 = (bc * middle)/ab; if(previous<0.000001) break; area1 = Area(ab1,ac1,bc1); area2 = area - area1; previous = middle; } if(area1/area2>= ratio) printf("Case %d: %lfn",caseNumber,middle); end = middle; else start = middle; middle = (start+end)/2;
  • 16. Similar • 1048 - Conquering Keokradong • 1056 - Olympics • 1076 - Get the Containers • 1138 - Trailing Zeroes (III) • 1276 - Very Lucky Numbers
  • 17. Bisection • Bisection -> two section • Divide elements to 2 part. • Then sort one part & use binary search.
  • 18. 1127 - Funny Knapsack • Given n integers and a knapsack of weight W, you have to count the number of combinations for which you can add the items in the knapsack without overflowing the weight. • Input • Input starts with an integer T (≤ 100), denoting the number of test cases. • Each case contains two integers n (1 ≤ n ≤ 30) and W (1 ≤ W ≤ 2 * 109) and the next line will contain n integers separated by spaces. The integers will be non negative and less than 109. • Output • For each set of input, print the case number and the number of possible combinations.
  • 19. Solution scanf("%d %d",&n,&k); for(i=0;i<n;i++) for(i=m;i<n;i++) scanf("%lld",&X[i]); { N3=N2; m = n/2; for(j=0;j<N2;j++) A[0]=0; { N1=1; B[N3]=B[j]+X[i]; B[0]=0; N3++; N2=1; } for(i=0;i<m;i++) N2=N3; { } N3=N1; for(j=0;j<N1;j++) sort(B,B+N2); { A[N3]=A[j]+X[i]; N3++; } N1=N3; }
  • 20. Solution total = 0; while(B[mid]>t) mid--; for(i=0;i<N1;i++) if(k>=A[i]) { while(mid+1<N2 && B[mid+1]<=t) t = k-A[i]; mid++; int left = 0; int right = N2 - 1; total += (mid+1); mid = (left+right)/2; } while(left<=right) { printf("Case %d: %dn",caseNumber,total); if(B[mid]==t) break; else if(B[mid]>t) right=mid-1; else left = mid+1; mid = (left+right)/2; }
  • 21. Similar • 1235 - Coin Change (IV)
  • 22. Ternary Search • A ternary search algorithm is a technique for finding the minimum or maximum of a unimodal function.
  • 23. Recursive algorithm def ternarySearch(f, left, right, absolutePrecision): if (right - left) < absolutePrecision: return (left + right)/2 leftThird = (2*left + right)/3 rightThird = (left + 2*right)/3 if f(leftThird) < f(rightThird): return ternarySearch(f, leftThird, right, absolutePrecision) else: return ternarySearch(f, left, rightThird, absolutePrecision)
  • 24. 1146 - Closest Distance • Two men are moving concurrently, one man is moving from A to B and other man is moving from C to D. Initially the first man is at A, and the second man is at C. They maintain constant velocities such that when the first man reaches B, at the same time the second man reaches D. You can assume that A, B, C and D are 2D Cartesian co-ordinates. You have to find the minimum Euclidean distance between them along their path.
  • 25. • Input • Input starts with an integer T (≤ 1000), denoting the number of test cases. • Each case will contain eight integers: Ax, Ay, Bx, By, Cx, Cy, Dx, Dy. All the co-ordinates are between 0 and 100. (Ax, Ay) denotes A. (Bx, By) denotes B and so on. • Output • For each case, print the case number and the minimum distance between them along their path. Errors less than 10-6 will be ignored.
  • 26. Solution void makePoint(double h1, double h2) { double h3 = (ax - h1)*(ax - h1) + (ay - h2) * (ay - h2); h3 = sqrt(h3); double h4 = dis - h3; mx = (cx * h4 + dx * h3)/dis; my = (cy * h4 + dy * h3)/dis; } double distance(double h1, double h2, double h3, double h4) { double h5 = (h1-h3)*(h1-h3) + (h2-h4)*(h2-h4); return sqrt(h5); }
  • 27. Solution dis = (ax - bx)*(ax - bx) + (ay - by) * (ay - by); dis = sqrt(dis); min = (ax - cx)*(ax - cx) + (ay - cy) * (ay - cy); min = sqrt(min); leftx = ax; lefty = ay; rightx = bx; righty = by; while(1) { rightThirdx = (leftx + 2*rightx)/3; leftThirdx = (2*leftx + rightx)/3; rightThirdy = (lefty + 2*righty)/3; leftThirdy = (2*lefty + righty)/3; makePoint(rightThirdx,rightThirdy); makePoint(leftThirdx,leftThirdy); disRight = disLeft = distance(leftThirdx,leftThirdy,mx,my); distance(rightThirdx,rightThirdy,mx,my);
  • 28. Solution if(disLeft<=disRight) min2 = min - min1; { if(min2<0) min2=-min2; rightx = rightThirdx; if(min2<0.0000000001) righty = rightThirdy; break; min1 = disLeft; min = min1; } } else printf("Case %ld: %lfn",cas1,min); { leftx = leftThirdx; lefty = leftThirdy; min1 = disRight; }
  • 29. Similar • 1240 - Point Segment Distance (3D)