NOIP2010 关押罪犯 (并查集)

若x,y有关系 将x与y的补集, y与x的补集建立关系 

const maxn=20008;
      maxm=100008;
var eg:array[0..maxm,1..3] of longint;
    f:array[0..maxn*2] of longint;
    i,j,m,n,x,y,z:longint;
procedure swap(var a,b:longint);
var c:longint;
begin
    c:=a;a:=b;b:=c;
end;
function find(x:longint):longint;
begin
    if f[x]=x then exit(x);
    f[x]:=find(f[x]);
    exit(f[x]);
end;
procedure sort(l,r:longint);
var i,j,x:longint;
begin
    i:=l; j:=r;
    x:=eg[(l+r) div 2,3];
    while i<=j do
    begin
        while eg[i,3]>x do inc(i);
        while x>eg[j,3] do dec(j);
        if i<=j then
        begin
            swap(eg[i,1],eg[j,1]);
            swap(eg[i,2],eg[j,2]);
            swap(eg[i,3],eg[j,3]);
            inc(i);
            dec(j);
        end;
    end;
    if i<r then sort(i,r);
    if l<j then sort(l,j);
end;
begin
    readln(n,m);
    for i:=1 to m do read(eg[i,1],eg[i,2],eg[i,3]);
    for i:=1 to n*2 do f[i]:=i;
    sort(1,m);
    for i:=1 to m do
    begin
        x:=find(eg[i,1]);
        y:=find(eg[i,2]);
        if x=y then
        begin
            writeln(eg[i,3]);
            exit;
        end;
        f[x]:=find(eg[i,2]+n);
        f[y]:=find(eg[i,1]+n);
    end;
    writeln(0);
end.
原文地址:https://www.cnblogs.com/rpSebastian/p/4285994.html