perimeter of a triangle
Time Limit: 2000/1000ms (Java/Others)
Problem Description:
There are n sticks, the length of stick i is ai, and we want to select 3 sticks from them to form a triangle with the longest perimeter. Please output the largest perimeter, or 0 if the triangle cannot be formed.
Input:
The input contains multiple sets of tests, the first line of each set of tests inputs an integer n ( 3≤n≤10^5 ); the second line inputs n integers ai (1≤ai≤10^6);
Output:
For each set of tests, output a number representing the maximum perimeter, or 0 if a triangle cannot be formed.
Sample Input:
5 2 3 4 5 10 4 5 4 20 10
Sample Output:
12 0 Problem-
solving ideas: This is a question in "Challenging Programming Contest (Second Edition)". The book says a solution of O(n³), and also specifically explains another solution of O(nlogn), Leave it to the reader to ponder. But for this problem, since the maximum range of n is 10^5, O(n³) cannot be used, but the solution of O(nlogn) should be used.
We know that the necessary and sufficient conditions for forming a triangle are: the longest side is less than the sum of the remaining two sides ; it is not difficult to imagine that we can enumerate all options in a triple loop, and then judge whether a triangle can be formed, and finally find the largest perimeter. . However, the time complexity of this algorithm is too large and it will time out!
Another way is to sort the sticks first, then compare only the three adjacent sticks, and finally pick the largest perimeter. This way it only takes one loop. Why is this possible? Reason: If the stick has been sorted in ascending order, there is a<b<c<d, if there is a+b>c and a+b>d, the program does not compare a+b and d, then whether this will be missed The situation leads to an error, no, because if a+b>d, then b+c must also be greater than d, and a+b is less than b+c, so the comparison of the numbers after a+b and d is redundant Yes, and if these two cases are true at the same time, we can only take the latter case, because we want to get the longest perimeter! ! ! That way it's just a matter of comparing the three adjacent sticks.
1 #include<bits/stdc++.h> 2 using namespace std; 3 int a[1000005],n; 4 int main(){ 5 while(cin>>n){ 6 for(int i=0;i<n;++i) 7 cin>>a[i]; 8 sort(a,a+n);//默认升序排序 9 int ans=0; 10 for(int i=0;i<n-2;++i){ 11 int len=a[i]+a[i+ 1 ]+a[i+ 2 ]; // The perimeter of the triangle is 12 if (a[i]+a[i+ 1 ]>a[i+ 2 ])ans=max( ans,len); // Conclusion 13 } 14 cout<<ans<< endl; 15 } 16 return 0 ; 17 }