Pie(最小身長差を求めて、dp)

7579 ワード

Pie
Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 895    Accepted Submission(s): 246
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人の女子学生の身長を入力します.
人数の少ない方と他の方をマッチングして、最小限の差を求めます.
男女の身長をそれぞれ並べ替える.人数の少ない方はabs(m-n+1)個人と一致する.
|m-n|<=100なので、一人で最大100人にマッチします.
あとは2次元で配列をスクロールすればいいです.
dp[i][j]男は女に対してj人の最小身長差を間違えた.
dp[i%2][k]=min(dp[(i-1)%2][k]+abs(a[i]-b[j]),dp[i%2][k-1])
なぜかsortがずっと間違っているqsortが正しい..
コード:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
const int INF=0x3f3f3f3f;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define SD(x) scanf("%lf",&x)
#define P_ printf(" ")
typedef long long LL;
const int MAXN=10010;
double dp[2][110],a[MAXN],b[MAXN];
int cmp(const void *a,const void *b)
{
    return *(double *)a < *(double *)b ? 1 : -1;
}
int main(){
    int n,m;
    while(~scanf("%d%d",&n,&m),n||m){
        if(n<=m){
            for(int i=1;i<=n;i++)SD(a[i]);
            for(int i=1;i<=m;i++)SD(b[i]);
        }
        else{
            swap(n,m);
            for(int i=1;i<=m;i++)SD(b[i]);
            for(int i=1;i<=n;i++)SD(a[i]);
        }
        qsort(a+1,n,sizeof(a[1]),cmp);
        qsort(b+1,m,sizeof(b[1]),cmp);
        int len=m-n+1;
        mem(dp,0);
        for(int i=1;i<=n;i++){
            dp[i%2][1]=dp[(i-1)%2][1]+abs(a[i]-b[i]);
            for(int k=2;k<=len;k++){
                int j=i+k-1;
                dp[i%2][k]=min(dp[(i-1)%2][k]+abs(a[i]-b[j]),dp[i%2][k-1]);
            }
        }
        printf("%.6lf
",dp[n%2][len]); } return 0; }