题意:有n根棍子,棍子i的长度为ai,想要从中选出3根棍子组成周长尽可能长的三角形,请输出最大的周长,若无法组成三角形则输出0。

 

解法:将输入的棍子长度进行排序,由最长开始,一次取出三根最长的棍子,判断:最长的棍子 < 其余两根棍子的长度之和

 

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 #define maxn 1000
 6 int n;
 7 int func(int a[]){
 8     sort(a, a + n);
 9     int res = 0;
10     for(int i=n-1; i>1; i--)
11     {
12         if(a[i] < a[i-1] + a[i-2])
13             return a[i] + a[i-1] + a[i-2];
14     }
15     return res;
16 }
17 
18 int main()
19 {
20 
21 
22     int a[maxn];
23     while(cin >> n)
24     {
25         for(int i=0; i<n; i++)
26             cin>>a[i];
27         int res = func(a);
28         cout<<res<<endl;
29     }
30 
31     return 0;
32 }

 

posted on 2017-06-02 21:06  pangzp  阅读(157)  评论(0编辑  收藏  举报