Newcoder 130 E.黑妹的游戏V(水~)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/V5ZSQ/article/details/82949050

Description

黑妹平时也很喜欢玩棋类游戏,但这次她在一块无限大的棋盘上玩游戏,她有 n n 枚棋子分别在 n n 个位置,她现在需要将其中k枚棋子移动到同一个位置组成一个超级棋子,棋子可以朝上下左右四个方向移动,现在你需要告诉她最小的移动步数是多少? 注意同一时刻可以允许多枚棋子在同一个位置。

Input

第一行一个整数 T T 表示数据组数。

对于每组数据:

第一行两个整数 n n k k ,分别表示棋子的个数和组成超级棋子的棋子个数。

下面 n n 行每行两个整数 x i , y i x_i,y_i 表示棋子的位置。

( 1 T 10 , 1 k n 100 , 1 0 9 x i , y i 1 0 9 ) (1\le T\le 10,1\le k\le n\le 100,-10^9\le x_i,y_i\le 10^9)

Output

对于每组数据输出一行表示答案。

Sample Input

1
3 2
2 4
1 2
3 5

Sample Output

2

Solution

所选 k k 个点最终位置必然可以是这 n n 个点中的某个横坐标和某个纵坐标,枚举汇聚点坐标,求出所有点到汇聚点的曼哈顿距离,排序后选择前 k k 小求和更新最优解即可

Code

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn=105;
int T,n,k,x[maxn],y[maxn];
ll a[maxn];
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&k);
		for(int i=1;i<=n;i++)scanf("%d%d",&x[i],&y[i]);
		ll ans=4e18;
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
			{
				for(int l=1;l<=n;l++)a[l]=(ll)abs(x[l]-x[i])+(ll)abs(y[l]-y[j]);
				sort(a+1,a+n+1);
				ll res=0;
				for(int l=1;l<=k;l++)res+=a[l];
				ans=min(ans,res);
			}
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/V5ZSQ/article/details/82949050
130