You are on page 1of 2

TÌM KIẾM TAM PHÂN

1. LƯU ĐỒ:

2. CODE:
#include<iostream>
#include<algorithm>
using namespace std;
int TimTP(int x,int B[],int idx1, int idx2){
int low=idx1,high=idx2,mid1=low+(high-low)/3,mid2=high-(high-low)/3,res;
if (B[mid1]==x || B[mid2]==x){
if (x==B[mid1]) res=mid1;
else res=mid2;
}
else{
if (B[mid1]>x){
high=mid1-1;
TimTP(x,B,low,high);
}
else if(x>B[mid2]){
low=mid2+1;
TimTP(x,B,low,high);
}
else{
low=mid1+1;
high=mid2-1;
TimTP(x,B,low,high);
}
}
return res;
}
int main()
{
int t; cin >> t;
while (t--){ //P3(CẢ BÀI): O(t.n.log(n))
int n; cin >> n;
int A[n],B[n];
for (int i=0;i<n;i++){ //P2: O(n.log(n))
cin >> A[i]; B[i]=A[i]; //CHỈ THỊ TÍCH CỰC P1. ĐỘ PHỨC TẠP: O(log(n))
}
sort(B,B+n);
bool ok=0;
for (int i=0;i<n;i++){
int res=TimTP(A[i],B,0,n-1);
if (B[res]==B[res+1] || B[res]==B[res-1]){
ok=1;
cout << A[i];
break;
}
}
if (!ok) cout << "NO";
cout << endl;
}
}
3. PHÂN TÍCH ĐỘ PHỨC TẠP:
- Chỉ thị tích cực có độ lớn là O(log(n))
- Tổng cả bài có độ lớn là O(t.n.log(n))

You might also like