bzoj 3362: [Usaco2004 Feb]Navigation Nightmare 导航噩梦 带权并查集

70 篇文章 0 订阅
68 篇文章 0 订阅

题目链接


【想说的话】

一道带权并查集好(水)题

以前觉得带权并查集挺屌的...

但是写过才发现就是正常的并查集顺便维护点什么东西...

好像我写的有点暴力啊...跑的好慢啊


【题解】

做并查集的过程中找根时不做路径压缩

然后对于每个点保存它到它的父亲节点需要在x轴和y轴上移动多少

每次合并x、y时找到y的根并记录从y移动到跟需要在x轴和y轴上移动多少

然后再把y的根的父亲设为x,将y的根的需要移动多少的值更新

最后询问就搞一搞就行了,我相信大家都会写=.=



代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>

using namespace std;

struct node1{
	int x,y,len;
	char way[2];
}edge[40040];

struct node2{
	int x,y,ti,num;
	friend bool operator < (node2 a,node2 b){
		return a.ti<b.ti;
	}
}que[40040];

int n,m,k;
int ans[40040];
int fa[40040];
int tox[40040],toy[40040];

int getroot(int x){
	if(fa[x]==x)return x;
	return getroot(fa[x]);
}

int getx(int x){
	if(fa[x]==x)return 0;
	return tox[x]+getx(fa[x]);
}

int gety(int x){
	if(fa[x]==x)return 0;
	return toy[x]+gety(fa[x]);
}

void un(int x,int y,int len,int to){
	int xx=getx(y);
	int yy=gety(y);
	y=getroot(y);
	fa[y]=x;
	tox[y]=-xx;
	toy[y]=-yy;
	if(to==1)toy[y]-=len;
	if(to==2)toy[y]+=len;
	if(to==3)tox[y]+=len;
	if(to==4)tox[y]-=len;
}

int main(){
	scanf("%d%d",&n,&m);
	for(int i=1; i<=n; i++)fa[i]=i;
	for(int i=1; i<=m; i++){
		scanf("%d%d%d%s",&edge[i].x,&edge[i].y,&edge[i].len,edge[i].way);
	}
	scanf("%d",&k);
	for(int i=0; i<k; i++){
		scanf("%d%d%d",&que[i].x,&que[i].y,&que[i].ti);
		que[i].num=i;
	}
	sort(que,que+k);
	int now=1;
	for(int i=0; i<k; i++){
		while(now<=que[i].ti && now<=m){
			if(edge[now].way[0]=='N')un(edge[now].x,edge[now].y,edge[now].len,1);
			if(edge[now].way[0]=='S')un(edge[now].x,edge[now].y,edge[now].len,2);
			if(edge[now].way[0]=='W')un(edge[now].x,edge[now].y,edge[now].len,3);
			if(edge[now].way[0]=='E')un(edge[now].x,edge[now].y,edge[now].len,4);
			now++;
		}
		if(getroot(que[i].x)!=getroot(que[i].y))ans[que[i].num]=-1;
		else ans[que[i].num]=abs(getx(que[i].x)-getx(que[i].y))+abs(gety(que[i].x)-gety(que[i].y));
	}
	for(int i=0; i<k; i++)printf("%d\n",ans[i]);
	
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值