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

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[N],b[N];
    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]);
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值