【POJ 1948】Triangular Pastures(dp—二维01背包)
Triangular Pastures
Description
Like everyone, cows enjoy variety. Their current fancy is new shapes for pastures. The old rectangular shapes are out of favor; new geometries are the favorite.
I. M. Hei, the lead cow pasture architect, is in charge of creating a triangular pasture surrounded by nice white fence rails. She is supplied with N (3 <= N <= 40) fence segments (each of integer length Li (1 <= Li <= 40) and must arrange them into a triangular pasture with the largest grazing area. Ms. Hei must use all the rails to create three sides of non-zero length. Help Ms. Hei convince the rest of the herd that plenty of grazing land will be available.Calculate the largest area that may be enclosed with a supplied set of fence segments. Input
* Line 1: A single integer N
* Lines 2..N+1: N lines, each with a single integer representing one fence segment's length. The lengths are not necessarily unique. Output
A single line with the integer that is the truncated integer representation of the largest possible enclosed area multiplied by 100. Output -1 if no triangle of positive area may be constructed.
Sample Input 5 1 1 3 3 4 Sample Output 692 Hint
[which is 100x the area of an equilateral triangle with side length 4]
Source |
[Submit] [Go Back] [Status] [Discuss]
[题意][给定一些树枝,要求全部用上,求能够围成的三角形的最大面积,如果不能围成三角形,那么输出-1]
【题解】【二维01背包】
【刚开始一直在考虑怎么样的三角形有最大的面积,一直在考虑怎么样才能把树枝较均匀的分配,然后。。。发现自己zz了,其实只要把能围成三角形的都试一遍不就好了,范围辣么小。。。】
【二维01背包,但在算面积时,要判断是否能围成三角形,然后用海伦公式计算面积即可】
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int f[2010][2010],n,a[2010],sum,m;
double ans;
inline int abss(int x)
{
if(x>=0) return x;
return -x;
}
inline bool check(int a,int b,int c)
{
if(a+b>c&&c>abss(a-b)&&a+c>b&&b>abss(a-c)&&b+c>a&&a>abss(b-c)) return 1;
return 0;
}
int main()
{
int i,j,k;
scanf("%d",&n);
for(i=1;i<=n;++i) scanf("%d",&a[i]),sum+=a[i];
m=sum;
f[0][0]=1;
for(i=1;i<=n;++i)
for(j=m;j>=0;--j)//m从最大值开始枚举才能保证包含所有的情况,我刚开始为了保证两边之和大于第三边,从一半开始枚举,然后WA、WA、WA!
for(k=m;k>=0;--k)
{
if (j-a[i]>=0) f[j][k]|=f[j-a[i]][k];
if (k-a[i]>=0) f[j][k]|=f[j][k-a[i]];
}//这个地方明白为什么写成 if(j-a[i]>=0&&f[j-a[i]][k]||k-a[i]>=0&&f[j][k-a[i]]) f[i][j]=1; 就会错。。。
for(i=m;i>0;--i)
for(j=m;j>0;--j)
if(f[i][j])
{
int c=sum-i-j;
if(!check(i,j,c)) continue;
double p=(double)sum/2.0;
double S=sqrt(p*(p-i)*(p-j)*(p-c));
ans=max(ans,S);
}
if(ans==0) printf("-1\n");
else printf("%.0lf\n",floor(ans*100));
return 0;
}
既然无能更改,又何必枉自寻烦忧