hdu 5135 枚举法

题目:

hdu 5135 枚举法_第1张图片

题目分析:可以先枚举所有可能构成的三角形,然后枚举所有搭配,选取最大值就可以了

代码如下:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#define MAX 15

using namespace std;

int n;
int s[MAX];
struct
{
    int s[4];
    double area;
}t[500];

bool check ( int a , int b , int c )
{
    if ( a + b <= c ) return false;
    if ( a + c <= b ) return false;
    if ( b + c <= a ) return false;
    return true; 
}

double cal ( int a , int b , int c )
{
    double p =( a + b +c )*1.0 / 2;
    return sqrt ( p*(p-a)*(p-b)*(p-c));
} 

int cnt;
int record[6], cc = 0;
double maxn = 0.0;

bool okay (  int index )
{
    for ( int i = 0 ; i < cc ; i++ )
    {
        for ( int j = 1 ; j < 4 ; j++ )
            for ( int k = 1 ; k < 4 ; k++ )
                if ( t[index].s[j] == t[record[i]].s[k] ) return false;
    }
    return true;
}

void dfs ( int size , int cur= 0 , double sum = 0.0  )
{
    if ( cc == size )
    {
        maxn = max ( maxn , sum );
        return;
    }
    for ( int i = cur ; i < cnt ; i++ )
        if ( okay( i ) )
        {
            record[cc++] = i;
            dfs ( size , i+1, sum + t[i].area );
            cc--;
        }
}

int main ( )
{
    while ( scanf ( "%d" , &n ) , n )
    {
        cnt = 0;
        for ( int i = 1 ; i <= n ; i++ ) scanf ( "%d" , &s[i] );
        for ( int i = 1 ; i < n-1 ; i++ )
         for ( int j = i+1 ; j < n ; j++ )
          for ( int k = j+1 ; k <= n ; k++ )
           if ( check ( s[i] , s[j] , s[k] ) )
           {
                t[cnt].s[1] = i;
                t[cnt].s[2] = j;
                t[cnt].s[3] = k;
                t[cnt++].area = cal ( s[i] , s[j] , s[k] );
           }
        maxn = 0.0;
        for ( int i = 1 ; i <= n/3 ; i++ )
        {
           cc = 0;
           dfs ( i );
        }
        printf ( "%.2f\n" , maxn ); 
    }
}


你可能感兴趣的:(枚举,C++,算法,ACM,HDU)