Minimal——dp

来源:互联网 发布:淘宝餐饮制售可以卖吗 编辑:程序博客网 时间:2024/06/05 15:44
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<<30using 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
原创粉丝点击