您的位置:首页 > 其它

HDU 3392 Pie(dp滚动数组+思路)

2017-07-15 08:47 351 查看


Pie

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1034    Accepted Submission(s): 288


Problem Description

A lot of boys and girls come to our company to pie friends. After we get their information, we need give each of them an advice for help. We know everyone’s height, and we believe that the less difference of a girl and a boy has, the better it is. We need to
find as more matches as possible, but the total difference of the matches must be minimum.

 

Input

The input consists of multiple test cases. The first line of each test case contains two integers, n, m (0 < n, m <= 10000), which are the number of boys and the number of girls. The next line contains n float numbers, indicating the height of each boy. The
last line of each test case contains m float numbers, indicating the height of each girl. You can assume that |n – m| <= 100 because we believe that there is no need to do with that if |n – m| > 100. All of the values of the height are between 1.5 and 2.0.

The last case is followed by a single line containing two zeros, which means the end of the input.

 

Output

Output the minimum total difference of the height. Please take it with six fractional digits.

 

Sample Input

2 3
1.5 2.0
1.5 1.7 2.0
0 0

 

Sample Output

0.000000

由于题目中给出|n – m| <= 100,因此肯定存在0~100个错位的情况,可以把两组数据分别排序,然后刷新错位时的最小值,可以用滚动数组优化时间(数组清零)和空间复杂度

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>

#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N=10005;
double dp[2][105];
int main()
{
int n,m;
double a
,b
;
while(~scanf("%d%d",&n,&m)&&n+m)
{
if(n<=m)//保证n为较小值,便于处理
{
for(int i=1; i<=n; i++)
scanf("%lf",&a[i]);
for(int i=1; i<=m; i++)
scanf("%lf",&b[i]);
}
else
{
for(int i=1; i<=n; i++)
scanf("%lf",&b[i]);
for(int i=1; i<=m; i++)
scanf("%lf",&a[i]);
swap(n,m);
}
sort(a+1,a+1+n);
sort(b+1,b+1+m);
int len=m-n+1;//最大错位数
mem(dp,0);
for(int i=1; i<=n; i++)
{
dp[i%2][1]=dp[(i-1)%2][1]+fabs(a[i]-b[i]);//原位的大小
for(int j=2; j<=len; j++)
{
int k=i+j-1;
dp[i%2][j]=min(dp[i%2][j-1],dp[(i-1)%2][j]+fabs(a[i]-b[k]));//刷新错位最小值
}
}
printf("%.6lf\n",dp[n%2][len]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: