POJ3375 Network Connection DP

此题当然不能用KM,但是我们可以根据KM的一个结论,最近距离一定不会相交,然后可以写出朴素的状态转移,时间复杂度M*N。然后显然,对于每一台电脑,最有的借口一定在 离他最近的借口 i的长度为n的领域内。因为题中M》=n时间复杂度降为N*N,问题解决。


此题容易拿WA的地方是是你找到的距离电脑最近的接口这一点。


Network Connection
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 |- 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 (1 ≤ M ≤ 100000), N (1 ≤ N ≤ 2000, N ≤ M). The following + 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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值