竞赛准备篇---(二)三角形(贪心)

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

限制条件:
 3 ≤ n ≤ 100

 1 ≤ ai ≤ 106

1.简单暴力:
直接三重循环枚举,如果可行更新最优解

2.贪心:

先排序,从大到小区最长的三根,如果可以构成三角形,直接输出,不行的话,去掉最长的。(因为最长的三根不能构成三角形,那说明最长的那一根太长了,所以必须去掉),剩下的n-1根同样的进行上述算法。时间复杂度O(nlog(n) + n)主要是排序的时间。

 1 #include<bits/stdc++.h> 
 2 #define FOR(i, a, b) for(int i = a; i < b; i++)
 3 using namespace std;
 4 const int maxn = 1e3 + 10;
 5 int a[maxn];
 6 int n;
 7 int solve()
 8 {
 9     sort(a, a + n);
10     for(int i = n - 1; i >= 2; i--)
11     {
12         if(a[i] < a[i - 1] + a[i - 2])return (a[i] + a[i - 1] + a[i - 2]);
13     } 
14     return 0;
15 }
16 int main()
17 {
18     cin >> n;
19     for(int i = 0; i < n; i++)cin >> a[i];
20     cout<<solve()<<endl;
21 }
NOIP普及组、提高组培训,有意可加微信fu19521308684
原文地址:https://www.cnblogs.com/fzl194/p/8666559.html