此题当然不能用KM,但是我们可以根据KM的一个结论,最近距离一定不会相交,然后可以写出朴素的状态转移,时间复杂度M*N。然后显然,对于每一台电脑,最有的借口一定在 离他最近的借口 i的长度为n的领域内。因为题中M》=n时间复杂度降为N*N,问题解决。
此题容易拿WA的地方是是你找到的距离电脑最近的接口这一点。
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3090 | Accepted: 673 |
Description
There are M network interfaces in the wall of aisle of library. And N computers next to the wall need to be connected to the network. A network interface can only connect with one computer at most. To connect an interface with coordinate x with a computer with coordinate y needs |x - y| unit of length of network cable. Your task is to minimize the total length of network cables to be used.
Input
The first line contains two integers M (1 ≤ M ≤ 100000), N (1 ≤ N ≤ 2000, N ≤ M). The following M + N lines each contains a integer coordinate. The first M coordinates are corresponding to the network interfaces, and the next N ones corresponding to the computers. All coordinates are arranged in [0, 1000000]. Distinct interfaces may have the same coordinate, so do the computers.
Output
Print an integer, representing minimum length of network cables to be used.
Sample Input
4 2 1 10 12 20 11 15
Sample Output
4
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
#define MAXN 5100
#define INF 0x3FFFFFFF
int m,n;
int f[2][MAXN],pos[MAXN];
int a[100000+10],b[MAXN];
int main()
{
while(~scanf("%d%d",&m,&n))
{
for(int i=1;i<=m;i++) scanf("%d",&a[i]);
for(int i=1;i<=n;i++) scanf("%d",&b[i]);
sort(a+1,a+1+m);
sort(b+1,b+1+n);
pos[0]=0;
int pp=1;
for(int i=1;i<=n;i++)
{
while(pp<=m&&a[pp]<=b[i])pp++;
pp--;
pos[i]=pp;
}
memset(f,0,sizeof(f));
int cur=0;
for(int i=1;i<=n;i++)
{
int l,r,s,e,fk=INF;
l=pos[i-1]-n;r=pos[i-1]+n;
s=pos[i]-n;e=pos[i]+n;
l=max(l,i-1);r=min(r,m);
s=max(s,i);e=min(e,m);
if(i==1) l=0,r=m;
f[cur^1][0]=INF;
for(int j=s,k=1;j<=e;j++,k++)
{
int tag=min(r,j-1);
f[cur^1][k]=min(f[cur^1][k-1],f[cur][tag-l+1]+abs(b[i]-a[j]));
}
cur^=1;
}
int l,r;
l=pos[n]-n,r=pos[n]+n;
l=max(l,n);r=min(r,m);
printf("%d\n",f[cur][m-l+1]);
}
return 0;
}