Network Connection
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 Source
POJ Monthly--2007.09.09, Updog
|
题意:
有m个接口(m<=100000),n台电脑(n<=2000),每台电脑对应一个接口,一个接口只能容纳一台电脑,电脑X如果连到接口Y,则需布线长度为|X-Y|,将所有的电脑布好,求最小的布线长度。
思路:
dp[i][j]表示前i台电脑连到前j个接口所需的最小花费,则有状态转移方程:
dp[i][j]=min(dp[i][j-1],dp[i-1][j-1]+abs(a[i]-b[j]));
复杂度为O(n*m),需要优化。
找到a[i]在b[]数组中的位置pos,则i对应的接口所在的区间范围为[pos-n,pos+n],那么复杂度就降为O(n*n)了。
空间开不下要用滚动数组,还有要注意的就是状态转移时要分情况,只有当前一个状态出现过才能转移到当前状态。
思路来源于:cms博客
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
//#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 2005
#define MAXN 100005
#define mod 1000000000
#define INF 0x3f3f3f3f
using namespace std;
int n,m,ans,flag;
int a[maxn],b[MAXN],pos[maxn];
int dp[2][MAXN];
void presolve()
{
int i,j;
sort(a+1,a+n+1);
sort(b+1,b+m+1);
for(i=1;i<=n;i++) // 预处理a[i]在b[]中的位置
{
pos[i]=lower_bound(b+1,b+m+1,a[i])-b;
}
}
void solve()
{
int i,j,p=1,s,e,ps,pe;
for(i=0;i<=m;i++)
{
dp[0][i]=0;
dp[1][i]=INF;
}
ps=0,pe=m;
for(i=1;i<=n;i++)
{
s=max(i,pos[i]-n-1); // 起点不能再i之前
e=min(pos[i]+n+1,m);
dp[p][s-1]=INF; // 将前一个位置置为INF
for(j=s;j<=e;j++)
{
if(j<=pe+1) dp[p][j]=min(dp[p][j-1],dp[p^1][j-1]+abs(a[i]-b[j]));//只有j-1的状态在前面出现过才能根据j-1的状态转移
else dp[p][j]=min(dp[p][j-1],dp[p^1][pe]+abs(a[i]-b[j]));//上一个状态没出现则只能由dp[p^1][pe]来推
}
ps=s,pe=e;
p=p^1;
}
ans=dp[p^1][e];
}
int main()
{
int i,j,t;
while(~scanf("%d%d",&m,&n))
{
for(i=1;i<=m;i++)
{
scanf("%d",&b[i]);
}
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
presolve();
solve();
printf("%d\n",ans);
}
return 0;
}