POJ 1948 Triangular Pastures (用所有的线段组成最大的三角形) DP || 携程员工运动会场地问题

来源:互联网 发布:如何设置淘宝客优惠券 编辑:程序博客网 时间:2024/04/30 13:24

Triangular Pastures
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions: 6336 Accepted: 2054

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

511334

Sample Output

692

Hint

[which is 100x the area of an equilateral triangle with side length 4] 

Source

USACO 2002 February

题意:给出n(n<=40)个长度小于等于40的线段,要求用上所有的线段,组成最大的三角形,求最大三角形面积的100倍。

思路:DP,dp[i][j]表示可以构成两条长度为i和j的边(自然第三条边也定下来了,但是不一定构成三角形)。然后就可以遍历所有的可能,取最大值即可。

转移方程:dp[j][k-a[i]] ==1 || dp[j-a[i]][k] == 1时,dp[j][k] = 1.

这里要注意两点:

一:总长度最大是40*40=1600,i和j的循环大小是800*800,总复杂度是O(40*800*800)=2*10^7复杂度。因为dp[j][k] 和 dp[k][j] 是等价的,可以把时间减一半,避免超时。

二:要注意线段长度的顺序,需要将长度按降序排序。

否则,3,4,5的话。第一趟dp,只能更新到dp[3][0] = 1;接下来第二趟就更新不到dp[3][4]或dp[4][3],。。。。。。最后就只能输出-1;降序排列之后就可以避免了!~

补二:突然又想到一种改法,可以不需要排序,而选择在更新到dp[3][0]的同时,把dp[0][3]也更新了,这样第二趟就可以更新到dp[4][3]了。也是可以过的。





代码:

#include<cstdio>#include<algorithm>#include<iostream>#include<cstring>#include<cmath>using namespace std;#define eps 1e-6#define maxn 45int a[maxn];bool dp[808][808];bool ok(int a,int b,int c){if(a+b>c && a+c>b && b+c>a)return 1;return 0;}double area(double a,double b,double c){double p = (a+b+c)/2;return sqrt(p*(p-a)*(p-b)*(p-c));}int cmp(int x,int y){return x>y;}int main(){int n;while(cin>>n){memset(dp,0,sizeof(dp));int sum = 0;for (int i = 0; i < n; i++){scanf("%d",&a[i]);sum += a[i];}//sort(a,a+n,cmp);/*排序也可做*/int half = sum/2;dp[0][0] = 1;for (int i = 0; i < n; i++)for (int j = half; j >= 0; j--)for (int k = j; k >= 0; k--){if((j >= a[i]&&dp[j-a[i]][k])||(k>=a[i]&&dp[j][k-a[i]]))dp[j][k] = 1, dp[k][j] = 1;//如果不排序就要两个都更新。}double ans = -1;for (int i = 1; i <= half; i++)for (int j = 1; j <= half; j++)if(dp[i][j] && ok(i,j,sum-i-j))ans = max(ans,100*area(i,j,sum-i-j));printf("%d\n",(int)ans);}return 0;}


0 0
原创粉丝点击