{
poj1236 network of schools
题目求:1.最少要发几个文件使得所有学校都能收到
2.最少连几条边使得所有学校连接
}
program network_of_schools;
var x,l,n,cnt,a,b,t,tot,i:longint;
head,dfn,low,s,belong:array[1..100]of longint;
in0,out0:array[1..100]of byte;
ins:array[1..100]of boolean;//在栈中
edge:array[1..10000,1..3]of longint;//一开始边数算错了,应该是最多任意两点间一条边100*100
function min(a,b:longint):longint;
begin
if a<b then min:=a else min:=b;
end;
procedure tarjan(i:longint);
var p,j,v:longint;
begin
t:=t+1;
s[t]:=i;
ins[i]:=true;
tot:=tot+1;
dfn[i]:=tot;
low[i]:=tot;
p:=head[i];
while p<>-1 do
begin
j:=edge[p,1];
if dfn[j]=0 then //未遍历
begin
tarjan(j);
low[i]:=min(low[i],low[j]); //公式j
end
else
if ins[j] then //j在栈中s
low[i]:=min(low[i],dfn[j]);
p:=edge[p,2];
end;
if low[i]=dfn[i] then //i是根
begin
cnt:=cnt+1;
repeat
v:=s[t];
t:=t-1; //出栈
ins[v]:=false;
belong[v]:=cnt; //看属于哪个强连通分量
until i=v;
end;
end;
begin
read(n);
for i:=1 to n do head[i]:=-1;
for i:=1 to n do
begin
read(x);
while x<>0 do
begin
l:=l+1;
edge[l,1]:=x;
edge[l,2]:=head[i];
edge[l,3]:=i; //前驱,缩点要用
head[i]:=l; //用静态链表存边的关系。
read(x);
end;
end;
fillchar(dfn,sizeof(dfn),0);
fillchar(low,sizeof(low),0);
fillchar(ins,sizeof(ins),false);
for i:=1 to n do
if dfn[i]=0 then //判断i点有没有被访问过,此处略去visit数组,因为dfn不为0一定是访问过的
tarjan(i);//tarjan
//缩点
for i:=1 to cnt do
begin
in0[i]:=1;//初始化表示i的入度为0
out0[i]:=1;
end;
for i:=1 to l do
if belong[edge[i,3]]<>belong[edge[i,1]] then //如果同一条边连接的两个点不在同一个强连通分量中
begin
in0[belong[edge[i,1]]]:=0;//后继的入度不是0
out0[belong[edge[i,3]]]:=0;//前驱的出度不是0
end;
for i:=1 to cnt do
begin
a:=a+in0[i];//入度为0的点的个数
b:=b+out0[i];//出度为0的点的个数
end;
writeln(a);
if cnt=1 then //只有一个强连通分量不用再添加边,要特殊判断!
writeln(0)
else
if a>b then writeln(a) else writeln(b);
//要使整个图为一个强连通分量最少添加的边d的条数=max(a,b),即使出度为0的点指到入度为0的点上
end.
①一开始脑子秀逗地算出最多边数为2*n,实际上最多任两个点间连一条边n*n个
这个一定要算对啊!!
②利用缩点可以看出最少添加的边的条数,但是如果最后缩为一个点,及只有一个强连通分量时,加边条数为0!否则正常进行