字节跳动9.20号笔试(C题)
最小曼哈顿距离
x轴,y轴分别排序,然后利用前缀和处理好所有出发位置的关系
然后利用二分查找,找到每个车站对应的与出发位置的关系
统计输出结果
时间复杂度O(min(m),min(n)),除开排序过程的复杂度
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cmath>
#define ll long long
using namespace std;
const int MIN=-2147483647;
const int MAX=2147483647;
const int Mod=1e9+7;
struct node{
int x,y;
int id;
}mp[100010];
struct station{
int x,y;
}st[100010];
bool cmpx(const node &a, const node &b) {
return a.x<b.x;
}
bool cmpy(const node &a,const node &b){
return a.y<b.y;
}
int sumx[100010]={0},sumy[100010]={0};
int ans[100010]={0};
int min_=MAX,ind=-1;
int main(){
freopen("c.txt","r",stdin);
int n,m;
while(scanf("%d %d",&n,&m)!=EOF){
if(n==0 && m==0) break;
for(int i=1;i<=n;i++){
scanf("%d %d",&mp[i].x,&mp[i].y);
mp[i].id=i;
}
for(int i=1;i<=m;i++){
scanf("%d %d",&st[i].x,&st[i].y);
}
//计算x轴,y轴对应前缀和
sort(mp+1,mp+n+1,cmpx);
for(int i=1;i<=n;i++) sumx[i]=sumx[i-1]+mp[mp[i].id].x;
//固定每个station,计算station到所有车站的距离(x轴)
for(int j=1;j<=m;j++){
int pos=lower_bound(sumx+1,sumx+n+1,st[j].x)-sumx;//>=
int t=st[j].x;
if(pos!=-1){
ans[j]=t*(pos-1)-sumx[pos-1]+sumx[n]-sumx[pos-1]-(n-pos+1)*t;
}
else{
ans[j]=t*n-sumx[n];
}
}
sort(mp+1,mp+n+1,cmpy);
for(int i=1;i<=m;i++) sumy[i]=sumy[i-1]+mp[mp[i].id].y;
//固定每个station,计算station到所有车站的距离(y轴)
for(int j=1;j<=m;j++){
int pos=lower_bound(sumy+1,sumy+n+1,st[j].y)-sumy;
int t=st[j].y;
if(pos!=-1){
ans[j]+=t*(pos-1)-sumy[pos-1]+sumy[n]-sumy[pos-1]-(n-pos+1)*t;
}
else{
ans[j]+=t*n-sumy[n];
}
//记录
if(ans[j]>min_){
min_=ans[j];
ind=j;
}
}
printf("%d %d\n",st[ind].x,st[ind].y);
}
return 0;
}