Description
We have N (N ≤ 10000) objects, and wish to classify them into several groups by judgement of their resemblance. To simply the model, each object has 2 indexes a and b (a, b ≤ 500). The resemblance of object i and object j is defined by dij = |ai - aj| + |bi -bj|, and then we say i is dij resemble to j. Now we want to find the minimum value of X, so that we can classify the N objects into K (K < N) groups, and in each group, one object is at most X resemble to another object in the same group, i.e, for every object i, if i is not the only member of the group, then there exists one object j (i ≠ j) in the same group that satisfies dij ≤ X
Input
The first line contains two integers N and K. The following N lines each contain two integers a and b, which describe a object.
Output
A single line contains the minimum X.
Sample Input
6 2 1 2 2 3 2 2 3 4 4 3 3 1
Sample Output
2
Source
POJ Monthly--2007.08.05, Li, Haoyuan
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
题目大意是求曼哈顿最小生成树中第n-k条边的长度,用来学曼哈顿最小生成树的~是莫队的基础?
求n个点曼哈顿距离最小生成树,如果用kruskal的话一一枚举建边会很慢,所以用到了这种神奇的算法。
对于每一个点,可能连边的点每45度都只有一个,所以用树状数组记录最小距离,然后每个方向更新~神奇的算法~
#include<cstdio>
#include<cstring>
#include<climits>
#include<iostream>
#include<algorithm>
using namespace std;
int n,k,fa[10001],c[4001],d[4001],tot;
struct node{
int x,y,num;
}a[10001];
struct node1{
int x,y,v;
}ed[40001];
bool cmp1(node u,node v)
{
return u.x==v.x ? u.y<v.y:u.x<v.x;
}
bool cmp2(node1 u,node1 v)
{
return u.v<v.v;
}
int findd(int u)
{
return fa[u]==u ? u:fa[u]=findd(fa[u]);
}
int lowbit(int u)
{
return u&(-u);
}
void query(int num,int pos,int val)
{
pos+=1000;
int now=-1,val1=INT_MAX;
for(int i=pos;i<4000;i+=lowbit(i))
if(val1>c[i])
{
val1=c[i];now=d[i];
}
if(now!=-1)
{
ed[++tot].x=num;ed[tot].y=now;ed[tot].v=val1-val;
}
}
void change(int num,int pos,int val)
{
pos+=1000;
for(int i=pos;i;i-=lowbit(i))
if(c[i]>val)
{
c[i]=val;d[i]=num;
}
}
void deal()
{
memset(c,63,sizeof(c));
sort(a+1,a+n+1,cmp1);
for(int i=n;i>=1;i--)
{
int pos=a[i].y-a[i].x,val=a[i].x+a[i].y;
query(a[i].num,pos,val);
change(a[i].num,pos,val);
}
}
int ans()
{
if(n==k) return 0;
deal();
for(int i=1;i<=n;i++) swap(a[i].x,a[i].y);deal();
for(int i=1;i<=n;i++) a[i].y=-a[i].y;deal();
for(int i=1;i<=n;i++) swap(a[i].x,a[i].y);deal();
sort(ed+1,ed+tot+1,cmp2);
for(int i=1;i<=tot;i++)
if(findd(ed[i].x)!=findd(ed[i].y))
{
fa[findd(ed[i].x)]=findd(ed[i].y);
n--;if(n==k) return ed[i].v;
}
}
int main()
{
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=n;i++) scanf("%d%d",&a[i].x,&a[i].y),a[i].num=i;
printf("%d\n",ans());
return 0;
}