需要在一个N × M的网格中建立一个通讯基站,通讯基站仅必须建立在格点上。
网格中有A个用户,每个用户的通讯代价是用户到基站欧几里得距离的平方。
网格中还有B个通讯公司,维护基站的代价是基站到最近的一个通讯公司的路程(路程定义为曼哈顿距离)。
在网格中建立基站的总代价是用户通讯代价的总和加上维护基站的代价,最小总代价。
输入
第一行为一个整数T,表示数据组数。
每组数据第一行为四个整数:N, M, A, B。
接下来的A+B行每行两个整数x, y,代表一个坐标,前A行表示各用户的坐标,后B行表示各通讯公司的坐标。
输出
对于每组数据输出一行"Case #X: Y",X代表数据编号(从1开始),Y代表所求最小代价。
数据范围
1 ≤ T ≤ 20
1 ≤ x ≤ N
1 ≤ y ≤ M
1 ≤ B ≤ 100
小数据
1 ≤ N, M ≤ 100
1 ≤ A ≤ 100
大数据
1 ≤ N, M ≤ 107
1 ≤ A ≤ 1000
2 3 3 4 1 1 2 2 1 2 3 3 2 2 2 4 4 4 2 1 2 2 4 3 1 4 3 1 4 1 3
Case #1: 4 Case #2: 13
本质就是求一元二次方程解的最小值
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<set>
#include<cmath>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define ll long long
using namespace std;
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,m,a,b,c,d;
cin>>n>>m>>a>>b;
int sx=0,sy=0,px=0,py=0;
for(int i=0;i<a;++i){
cin>>c>>d;
sx+=c*c;
px+=c;
sy+=d*d;
py+=d;
}
int min=100000000;
for(int i=0;i<b;++i){
cin>>c>>d;
int s1=100000000,s2=100000000;
for(int i=px/a-2;i<=px/a+2;++i){
int g=sx-2*px*i+a*i*i+abs(i-c);
if(g<s1)
s1=g;
}
for(int i=py/a-2;i<=py/a+2;++i){ //因为要求的是整数解,所以要计算左右边界
int g=sy-2*py*i+a*i*i+abs(i-d);
if(g<s2)
s2=g;
}
if(s1+s2<min)
min=s1+s2;
}
cout<<min<<endl;
}
return 0;
}
Case #1: 4 Case #2: 13
本质就是求一元二次方程解的最小值