UVA 1329 Corporative Network

利用并查集的路径压缩来更新距离

#include <stdio.h>

const int max_n = 20000+100;

struct node{
	int len2father;
	int father_index;
};
struct node node_arr[max_n];

int _abs(int n){
	return n<0 ? n*(-1) : n;
}

void merge(int child, int father){
	node_arr[child].father_index = father;
	node_arr[child].len2father = _abs(child-father)%1000;
}


//update the length between the child node and the father node while compressing the path
int get_root(int child){
	int root, father;
	if(node_arr[child].father_index == child){
		return child;
	}

	father = node_arr[child].father_index;
	root = get_root(father);
	node_arr[child].len2father += node_arr[father].len2father;
	node_arr[child].father_index = root;
	return root;
}

int main(void){
	int case_n, node_n, i;
	int child, father;
	char oper[10];
	//freopen("input.dat", "r", stdin);

	scanf("%d", &case_n);
	while(case_n--){
		scanf("%d", &node_n);
		//init
		for(i=1; i<=node_n; i++){
			node_arr[i].father_index = i;
			node_arr[i].len2father = 0;
		}
		while(1){
			scanf("%s", oper);
			if('O' == *oper)
				break;

			if('I' == *oper){
				scanf("%d %d", &child, &father);
				merge(child, father); //when merging, don't compress the path
			}
			else if('E' == *oper){
				scanf("%d", &child);
				get_root(child);
				printf("%d\n", node_arr[child].len2father ); //only compress the path when search the root index
			}
		}
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值