Another Minimum Spanning Tree UVALive - 3662 曼哈顿最小生成树

博客给出题目链接https://cn.vjudge.net/problem/UVALive - 3662,题意为输出曼哈顿最小生成树的总距离和,还提供了模板题讲解链接https://blog.youkuaiyun.com/mmk27_word/article/details/90408272。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://cn.vjudge.net/problem/UVALive-3662

题意:输出曼哈顿最小生成树的总距离和

题解:模板题,讲解:https://blog.youkuaiyun.com/mmk27_word/article/details/90408272

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f
#define lowbit(x) x&(-x)
typedef long long ll;
const int N=100100;
struct Point{
	int x,y;
	int y_x;
	int id;
	bool operator <(const Point &xx)const
	{
		if(x!=xx.x) return x<xx.x;
		else return y<xx.y;
	}
}p[N];
int n,k;
int b[N],len;
int sum[N],posid[N];
// 树状数组维护 大于等于(y-x) 最小的(x+y) 的对应的编号 
void update(int x,int d,int id)
{
	while(x)
	{
		if(d<sum[x])
		{
			sum[x]=d;
			posid[x]=id;
		}
		x-=lowbit(x); 
	}
}
int query(int x)
{
	int minn=INF,id=-1;
	while(x<=len)
	{
		if(sum[x]<minn)
		{
			minn=sum[x];
			id=posid[x];
		}
		x+=lowbit(x);
	}
	return id;
}
int dis(Point x,Point y)
{
	return abs(x.x-y.x)+abs(x.y-y.y);
}
struct edge{
	int u,v,d;
	bool operator <(const edge &x)const
	{
		return d<x.d;
	}
}e[N*4];
int tot;
void addedge(int x,int y,int d)  // 记录储存的边 
{
	tot++;
	e[tot].u=x;
	e[tot].v=y;
	e[tot].d=d;
}
int f[N];
int fath(int x)
{
	return x==f[x]?x:f[x]=fath(f[x]);
}
void init()
{
	for(int i=1;i<=n;i++)
	{
		f[i]=i;
	}
	tot=0;
}
int main()
{
	int ca=1;
	int pos,cnt;
	int x,y;
	ll ans;
	while(~scanf("%d",&n) && n)
	{
		init();
		for(int i=1;i<=n;i++)
		{
			scanf("%d%d",&p[i].x,&p[i].y);
			p[i].id=i;
		}
		
		for(int i=0;i<4;i++)
		{
			if(i==1||i==3)
			{
				for(int j=1;j<=n;j++)
					swap(p[j].x,p[j].y);
			}
			else if(i==2)
			{
				for(int j=1;j<=n;j++)
					p[j].x=-p[j].x;
			}
			for(int j=1;j<=n;j++)
			{
				p[j].y_x=p[j].y-p[j].x;
				b[j]=p[j].y_x;	
			}
			// 离散化 (y-x) 
			sort(b+1,b+1+n);
			len=unique(b+1,b+1+n)-(b+1);
			
			sort(p+1,p+1+n);
			for(int j=1;j<=len;j++)sum[j]=INF;
			for(int j=n;j>=1;j--)
			{
				pos=lower_bound(b+1,b+1+len,p[j].y_x)-b;
				cnt=query(pos);
				if(cnt!=-1) addedge(p[j].id,p[cnt].id,dis(p[j],p[cnt])); // 加边 
				update(pos,p[j].x+p[j].y,j);
			}
		}
		sort(e+1,e+1+tot);
		cnt=0;
		ans=0;   // 求生成树距离和 
		for(int i=1;i<=tot;i++)
		{
			x=fath(e[i].u);
			y=fath(e[i].v);
			if(x==y) continue;
			f[x]=y;
			cnt++;
			ans+=1LL*e[i].d;
			if(cnt==n-1)
			{
				
				break;
			}
		}
		printf("Case %d: Total Weight = %lld\n",ca++,ans);
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值