3A87 @ 2023-05-21 14:20:27
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=100010;
int m,n;
int school[N],stu[N];
int main()
{
scanf("%d %d",&m,&n);
for(int i=1;i<=m;i++)
scanf("%d",&school[i]);
for(int i=1;i<=n;i++)
scanf("%d",&stu[i]);
sort(school+1,school+1+n);
long long sum=0;
for(int j=1;j<=n;j++)
{
int l=0,r=m;
int ans=1e9;
while(l+1<r)
{
int mid=(l+r)/2;
if(school[mid]==stu[j])
{
ans=0;
break;
}
else if(school[mid]<stu[j])
{
ans=min(ans,abs(school[mid]-stu[j]));
l=mid;
}
else
{
ans=min(ans,abs(school[mid]-stu[j]));
r=mid;
}
}
sum+=ans;
}
printf("%lld\n",sum);
return 0;
}
by Bai_cen @ 2023-07-27 20:08:41
@3A87
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=100010;
int m,n;
int school[N],stu[N];
int main()
{
scanf("%d %d",&m,&n);
for(int i=1;i<=m;i++)
scanf("%d",&school[i]);
for(int i=1;i<=n;i++)
scanf("%d",&stu[i]);
sort(school+1,school+1+n);
long long sum=0;
for(int j=1;j<=n;j++)
{
int l=0,r=m;
int ans=1e9;
while(l+1<r)
{
int mid=(l+r)/2;
if(school[mid]==stu[j])
{
ans=0;
break;
}
else if(school[mid]<stu[j])
{
ans=min(ans,abs(school[mid]-stu[j]));
l=mid + 1;
}
else
{
ans=min(ans,abs(school[mid]-stu[j]));
r=mid - 1;
}
}
sum+=ans;
}
printf("%lld\n",sum);
return 0;
}
试试?