Sicily 1828. Minimal

1828. Minimal

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

There are two sets S 1 and S subjecting to:
(1) S 1, S are both the subsets of {x | x is an integer and 0  < x  < 1,000,000}
(2) 0 < |S 1 |  < |S 2< 500
 
F(S 1 ,S 2) = min {|a 1-b 1| + |a 2 – b 2| + … + | a –b N |}
in which a i ∈S 1, b i ∈S 2
                      a≠aif i≠j
                      b≠bif i≠j

(i, j = 1, 2 … NN = | S1|)

Input

The first line contains an integer indicating the number of test cases.
For each test case, there are two integers N and M in the first line. N is the number of elements in S 1 while M is the number of elements in S 2. There are N+M lines that follow. In the first N lines are the integers in S 1, while the last M lines S 2.There is NO bland line between two cases.

Output

For each test case, print the result of F(S 1 ,S 2), one case per line. There is NO bland line between two cases.

Sample Input

1
2 3
30
20
50
10
40

Sample Output

20

// Problem#: 1828
// Submission#: 3342649
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <queue>
#include <string.h>
#include <vector>
#include <iomanip>
#include <map>
#include <stack>
#include <functional>
#include <list>
#include <cmath>
using namespace std;

const int MAX_N = 505;
const int INF = 99999999;

int a[MAX_N], b[MAX_N];
int dp[MAX_N][MAX_N];

int main() {

    std::ios::sync_with_stdio(false);
    int caseNum;
    cin >> caseNum;

    while (caseNum--) {
        int N, M;
        cin >> N >> M;
        for (int i = 1; i <= N; i++) cin >> a[i];
        for (int i = 1; i <= M; i++) cin >> b[i];
        sort(a + 1, a + N + 1);
        sort(b + 1, b + M + 1);
        for (int i = 1; i <= N; i++) {
            if (i == 1) dp[i][i] = abs(a[i] - b[i]);
            else dp[i][i] = dp[i - 1][i - 1] + abs(a[i] - b[i]);
        }
        for (int i = 1; i <= N; i++) {
            for (int j = i + 1; j <= M; j++) {
                dp[i][j] = min(dp[i - 1][j - 1] + abs(a[i] - b[j]), dp[i][j - 1]);
            }
        }
        cout << dp[N][M] << endl;
    }


    //getchar();
    //getchar();
    
    return 0;
}                                 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值