Description
A number of schools are connected to a computer network. Agreements have been developed among those schools: each school maintains a list of schools to which it distributes software (the “receiving schools”). Note that if B is in the distribution list of school A, then A does not necessarily appear in the list of school B
You are to write a program that computes the minimal number of schools that must receive a copy of the new software in order for the software to reach all schools in the network according to the agreement (Subtask A). As a further task, we want to ensure that by sending the copy of new software to an arbitrary school, this software will reach all schools in the network. To achieve this goal we may have to extend the lists of receivers by new members. Compute the minimal number of extensions that have to be made so that whatever school we send the new software to, it will reach all other schools (Subtask B). One extension means introducing one new member into the list of receivers of one school.
【题目分析】
强连通分量的缩点
首先找连通分量,然后看连通分量的入度为0点的总数,出度为0点的总数,那么问要向多少学校发放软件,就是入度为零的个数,这样才能保证所有点能够找到
然后第二问添加多少条边可以得到使整个图达到一个强连通分量,答案是入度为0的个数和出度为0的个数中最大的
那个,为什么会这样呢,经过我同学的讨论,将这个图的所有子树找出来,然后将一棵子树的叶子结点(出度为0)连到另外一棵子树的根结点上(入度为0),这样将所有的叶子结点和根节点全部消掉之后,就可以得到一整个强连通分量,看最少多少条边,这样就是看叶子结点和根节点哪个多,即出度为0和入度为0哪个多
【代码】
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAXV 110
#define min(a,b) (a>b?b:a)
#define max(a,b) (a>b?a:b)
int n,map[MAXV][MAXV],outdegree[MAXV],indegree[MAXV];
int dfn[MAXV];
int low[MAXV];
int stap[MAXV],stop;
bool instack[MAXV];
int count;
int cnt;
int belong[MAXV];
void init(){
count=stop=cnt=0;
memset(instack,false,sizeof(instack));
memset(map,0,sizeof(map));
memset(dfn,0,sizeof(dfn));
}
void tarjan(int x){
int i;
dfn[x]=low[x]=++cnt;
stap[stop++]=x;
instack[x]=true;
for(i=1;i<=n;i++){
if(!map[x][i]) continue;
if(!dfn[i]){
tarjan(i);
low[x]=min(low[i],low[x]);
}else if(instack[i])
low[x]=min(dfn[i],low[x]);
}
if(low[x]==dfn[x]){
count++;
while(1){
int tmp=stap[--stop];
belong[tmp]=count;
instack[tmp]=false;
if(tmp==x) break;
}
}
}
void output(){
int i,j,inzero=0,outzero=0;
for(i=1;i<=n;i++){
indegree[i]=outdegree[i]=0;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(map[i][j] && belong[i]!=belong[j]){
indegree[belong[j]]++;
outdegree[belong[i]]++;
}
for(i=1;i<=count;i++){
if(!indegree[i]) inzero++;
if(!outdegree[i]) outzero++;
}
if(count==1)
printf("1\n0\n");
else
printf("%d\n%d\n",inzero,max(inzero,outzero));
}
int main(){
int i,a;
while(~scanf("%d",&n)){
init();
for(i=1;i<=n;i++){
while(scanf("%d",&a) && a) map[i][a]=1;
}
for(i=1;i<=n;i++)
if(!dfn[i]) tarjan(i);
output();
}
return 0;
}