贪心 + 数学模板题。。。
知三角形三边,求面积方式:
三角形三边长分别为: a、b、c;
设:p=(a+b+c)/2
则:三角形的面积S=sqrt(p(p-a)(p-b)(p-c));
一点贪心思想:将边长从大到小进行排序,从最长的三边开始选,
如果相邻三边可以围成三角形,则其比为结果三角形中的一个;
如果围不成,舍弃最长边,再向下寻找相邻三条边。
AC Code:
1 // 2 // main.cpp 3 // 20141104 4 // 5 // Created by songjs on 14-11-4. 6 // Copyright (c) 2014年 songjs. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <stdio.h> 11 #include <algorithm> 12 #include <cstring> 13 #include <string.h> 14 #include <math.h> 15 #include <queue> 16 #include <stack> 17 #include <stdlib.h> 18 #include <map> 19 using namespace std; 20 #define LL long long 21 #define sf(a) scanf("%d",&(a)); 22 23 #define N 10020 24 int f[20]; 25 int a[20]; 26 double jud(int x){ 27 //从x往前的三个数字,是否可以组成三角形,如果可以,那么其面积为多少。 28 for(int i=0;i<3;i++) a[i] = f[x--]; 29 sort(a,a+3); //从小到大 30 //printf("判断: %d %d %d\n",a[0],a[1],a[2]); 31 if(a[0]+a[1]<=a[2]) return -1.0; //构不成三角形 32 double p = ((double)a[0] + a[1] + a[2])/2.0; 33 return sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])); 34 } 35 36 //p=(a+b+c)/2,三角形的面积为S 37 //则S^2=p(p-a)(p-b)(p-c) 38 int main() 39 { 40 int n; 41 while(scanf("%d",&n) && n){ 42 for(int i=0;i<n;i++) scanf("%d",&f[i]); 43 sort(f,f+n); 44 double num =0.0; 45 int i; 46 for(i=n-1;i>=2;i--){ 47 double t =jud(i); 48 if(t >= 0.0) { 49 num += t; 50 i = i - 2; 51 } 52 } 53 printf("%.2f\n",num); 54 } 55 // 3 3 4 4 5 5 90 56 57 58 return 0; 59 }