码迷,mamicode.com
首页 > 编程语言 > 详细

算法模板——并查集

时间:2015-01-20 23:32:35      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

实现功能——操作1:将两个数字合并到一个集合内;操作2:判断两个数字是否在一起

第6行是亮点,这个优化能快出不少,真的

 1 var
 2    i,j,k,l,m,n:longint;
 3    c:array[0..100000] of longint;
 4 function getfat(x:longint):longint;inline;
 5          begin
 6               if c[x]<>x then c[x]:=getfat(c[x]);   //亮点在这里么么哒
 7               exit(c[x]);
 8          end;
 9 begin
10      readln(n);
11      for i:=1 to n do c[i]:=i;
12      while true do
13            begin
14                 read(i);if (i<1) or (i>2) then halt;
15                 readln(j,k);
16                 case i of
17                      1:c[getfat(j)]:=getfat(k);    //合并
18                      2:if getfat(j)=getfat(k) then writeln(Together!) else writeln(Not together!); //判断是否已合并
19                 end;
20            end;
21 end.
22              

 

算法模板——并查集

标签:

原文地址:http://www.cnblogs.com/HansBug/p/4237543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!