Light OJ 1307 - Counting Triangles Solution
The time complexity can be greatly reduced using Two Pointer methods in just two nested loops.
- Approach: First sort the array, and run a nested loop, fix an index and then try to fix an upper and lower index within which we can use all the lengths to form a triangle with that fixed index.
- Algorithm:
- Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array.
- Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1
- Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed
from a[l+1], a[l+2]…..a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than r - If triangle cannot be formed using arr[l] and arr[r] then increment the value of r and continue the loop till l is less than r
- So the overall complexity of iterating
through all array elements reduces.
Solution in C++:
///**********ALLAH IS ALMIGHTY************///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- int n,i,t,k;
- cin>>t;
- for(k=1; k<=t; k++)
- {
- cin>>n;
- int ar[n+1];
- for(i=0; i<n; i++)
- {
- cin>>ar[i];
- }
- sort(ar,ar+n);
- int l,r;
- int cnt=0;
- for(i=n-1; i>=1; i--)
- {
- l=0;
- r=i-1;
- while(r>l)
- {
- if(ar[l]+ar[r]>ar[i])
- {
- cnt+=(r-l);
- r--;
- }
- else
- l++;
- }
- }
- printf("Case %d: %d\n",k,cnt);
- }
- return 0;
- }
No comments