Sicily 1828. Minimal

  1. Minimal
    Constraints
    Time Limit: 1 secs, Memory Limit: 32 MB
    Description
    There are two sets S1 and S2 subjecting to:
  • 4 -
    (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
    这道题是 AB 两个集合,在 B 集合中找出一个子集合,其中元素个数和 A 中相
    同,按照顺序依次减下去,计算出差的绝对值的最小值
    首先要进行排序
    假设 S1 中有了 a1,a2,S2 中有 b1,b2
    且 a1<=a2,b1<=b2
    那么有|a1-b1|+|a2-b2|<=|a1-b2|+|a2-b1|
    所以从小到大一个个匹配不会更差,只会更好然后就要从集合 B 中挑选数字,
    我们可以用一个数组 dp[i][j]来存储取 A 集合的前 i 个数字和 B 集合的前 j 个数
    字的差的绝对值的最小值,则当我们计算 dp[i][j]的时候可以考虑到底用不用 B
    集合里面的第 j 个数字,若使用的话,则该数字为当前 B 集合中最大的数字,
    一 定 和 A 集 合 中 最 大 的 , 也 就 是 第 i 个 元 素 匹 配 , 这 种 情 况 是
    dp[i][j]=dp[i-1][j-1]+abs(A[i]-B[j]),另一种情况是没有使用 B 中的第 j 个数字,这
    种 情 况 就 是 dp[i][j-1], 所 以 可 得 状 态 方 程
    dp[i][j]=min(dp[i-1][j-1]+abs(A[i]-B[j]),dp[i][j-1])(i<j),而 i>j 时,不妨设 dp[i][j]
    为 INF
#include<iostream> 
#include<cstring>
#include<vector>
#include<algorithm>
#define INF 1<<30
using namespace std;
long long int dp[505][505];
int main(){
	int n;
	cin>>n;
	while(n--){
		memset(dp,0,sizeof(dp));
		int numa,numb;
		int v1[505];
		int v2[505];
		cin>>numa>>numb;
		int a,b;
		for(int i=1;i<=numa;i++){
			cin>>v1[i];
			//v1.push_back(a);
		}
		for(int i=1;i<=numb;i++){
			cin>>v2[i];
		//	v2.push_back(b);
		}
		sort(v1+1,v1+numa+1);
		sort(v2+1,v2+numb+1);
		int result=0;
		for(int i=0;i<=numb;i++){
			dp[0][i]=0;
		}
		//dp[0][0]=0;
		for(int i=1;i<=numa;i++){
			for(int j=0;j<=numb;j++){
				if(i>j){
					dp[i][j]=INF;
				}
				else{
					dp[i][j]=min(dp[i][j-1],dp[i-1][j-1]+abs(v1[i]-v2[j]));
				}
			}
		}
		cout<<dp[numa][numb]<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/dcy19991116/article/details/89055012
今日推荐