Mahmoud and a Triangle (CodeForces - 766B) 思維
Mahmoud has n line segments, the i-th of them has length ai. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3
Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
InputThe first line contains single integer n (3 ≤ n ≤ 105) — the number of line segments Mahmoud has.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the lengths of line segments Mahmoud has.
OutputIn the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise.
Example Input5 1 5 3 2 4
YESInput
3 4 1 2Output
NONote
For the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle.
不要上來就三層for迴圈暴力,我們提倡和平。分析一下會發現很簡單
分析:首先進行排序。因為三角形滿足任意兩邊之和大於第三邊(a+b>c),任意兩邊之差小於第三邊(c-b<a)。所以使得a+b儘可能大,c儘可能小。那麼可以取連續的三個數進行判斷即可。
#include <iostream>
#include <algorithm>
using namespace std;
long num[100005];
int main(){
int n;
cin>>n;
for(int i = 0; i<n; i++)
cin>>num[i];
sort(num, num+n);
for(int i = 0; i + 2<n; i++){
if(num[i] + num[i+1] > num[i+2]){
cout<<"YES"<<endl;
return 0;
}
}
cout<<"NO"<<endl;
return 0;
}