一、一些概念
xor:亦或,相同为0,不同为1
or:或,有一个为1则为1
本题中用0代表平行,1代表垂直
way[i]表示i与i的father[i]是垂直还是平行(值为0或1)
题目中读入的平行垂直关系和way[]表示的都是两个直线之间的平行垂直关系,因此都用xor运算
二、并查集的程序段
1、初始化
for i:=1 to n do
begin
father[i]:=i;
way[i]:=0;
end;
2、找父亲
function getfather(x:longint):longint;
var t:longint;
begin
if father[x]=x then exit(x);
t:=father[x];
father[x]:=getfather(t);//压缩路径
way[x]:=way[t] xor way[x];//在找父亲的过程中一层层合并,最终直接指向最远的父亲;且getfather的过程在getdata之前完成
getfather:=father[x];//每一次都返回最远的父亲
end;
3、得到两个元素之间的关系
function getdata(x,y:longint):longint;
begin
getdata:=way[x] xor way[y];
end;
4、合并两个元素
proedure union(x,y,d:longint);
var a,b:longint;
begin
a:=getfather(x);
b:=getfather(y);
father[a]:=b;
way[a]:=way[x] xor d xor way[y];
end;
三、code
program tt;
var a,b,b1,a1,i,j,n,m,q,d,ans:longint;
father:array[1..1000]of longint;
way:array[1..1000]of byte;
ch,s2:char;
function getfather(x:longint):longint;
var t:longint;
begin
if father[x]=x then exit(x);
t:=father[x];
father[x]:=getfather(t);
way[x]:=way[t] xor way[x];
getfather:=father[x];
end;
function getdata(a,b:longint):longint;
begin
getdata:=way[a] xor way[b];
end;
procedure union(x,y,d:longint);
var a,b:longint;
begin
a:=getfather(x);
b:=getfather(y);
father[a]:=b;
way[a]:=way[a1] xor d xor way[b1];//这里x,y的值会变!!,要用原始的a1,b1
end;
begin
readln(n,m,q);
for i:=1 to n do begin father[i]:=i;way[i]:=0;end;
for i:=1 to m do
begin
readln(ch,a1,ch,s2,ch,ch,b1);
if s2='p' then d:=0 else d:=1;
a:=getfather(a1);
b:=getfather(b1);
if a<>b then
union(a,b,d)
else
if getdata(a1,b1)<>d then
begin
writeln('There must be something wrong...');
exit;
end;
end;
for i:=1 to n-1 do
for j:=i+1 to n do
begin
a:=getfather(i);
b:=getfather(j);
if (a=b)and(getdata(i,j)=0) then ans:=ans+1;
end;
writeln(ans);
for i:=1 to q do
begin
readln(ch,a1,ch,ch,b1);
a:=getfather(a1);
b:=getfather(b1);
if a<>b then
writeln('No idea.')
else
if getdata(a1,b1)=0 then writeln('Parallel.') else writeln('Vertical.');
end;
end.