bzoj 1370 團伙 並查集
阿新 • • 發佈:2019-02-06
題意:n個人,朋友的朋友是我的朋友,敵人的敵人是我的朋友,互為朋友的組成一個團伙,問團伙的數量
並查集入門題
把一個人拆成兩個,x表示朋友集合,n+x表示敵人集合
朋友的朋友是我的朋友:直接合並x和y
敵人的敵人是我的朋友:合併x和n+y ,合併 y 和n+1
——by Eirlysvar n,m,x,y,ans :longint; vis :array[0..2010] of boolean; f :array[0..2010] of longint; i :longint; ch :char; function get_father(x:longint):longint; begin if x=f[x] then exit(x); f[x]:=get_father(f[x]); exit(f[x]); end; procedure connect(x,y:longint); begin x:=get_father(x); y:=get_father(y); if (x<>y) then f[x]:=y; end; begin read(n); for i:=1 to 2*n do f[i]:=i; readln(m); for i:=1 to m do begin read(ch); readln(x,y); if ch='F' then connect(x,y) else begin connect(x,n+y); connect(y,n+x); end; end; ans:=0; for i:=1 to n do begin x:=get_father(i); if not vis[x] then begin inc(ans); vis[x]:=true; end; end; writeln(ans); end.