Minimal——dp

Problem Description
There are two sets S1 and S2 subjecting to:
(1) S1, S2 are both the subsets of {x | x is an integer and 0 < x < 1,000,000}
(2) 0 < |S1 | < |S2| < 500
F(S1 ,S2) = min {|a1-b1| + |a2 – b2| + … + | aN –bN |}
in which ai ∈S1, bi ∈S2
ai ≠aj if i≠j
bi ≠bj if i≠j
(i, j = 1, 2 … N,N = | 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 S1 while M is the number of elements in S2. There are N+M lines that follow. In the first N lines are the integers in S1, while the last M lines S2. There is NO bland line between two cases.
Output
For each test case, print the result of F(S1 ,S2), 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

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<cmath>
#define Max 505
#define INF 1<<30
using namespace std;
int dp[Max][Max],a[Max],b[Max];
int m,n;
void get_answer()
{
	    int i,j,k;
        sort(a+1,a+m+1);
		sort(b+1,b+n+1);
		for(i=1;i<=m;i++)
			for(j=1;j<=n;j++)
				dp[i][j]=INF;
			dp[0][0]=0;
			for(i=1;i<=m;i++)
				for(j=i;j<=n;j++)
				{
					for(k=i-1;k<j;k++)
						if(dp[i][j]>dp[i-1][k]+abs(a[i]-b[j]))
							dp[i][j]=dp[i-1][k]+abs(a[i]-b[j]);
				}
				int ans=INF;
				for(i=m;i<=n;i++)
					if(dp[m][i]<ans)
						ans=dp[m][i];
					printf("%d\n",ans);
}
int main()
{
	freopen("b.txt","r",stdin);
	int t,i;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d",&m,&n);
		for(i=1;i<=m;i++)
			scanf("%d",&a[i]);
		for(i=1;i<=n;i++)
			scanf("%d",&b[i]);
		get_answer();
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值