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.
Input
The first line contains an integer N: the number of schools in the network (2 <= N <= 100). The schools are identified by the first N positive integers. Each of the next N lines describes a list of receivers. The line i+1 contains the identifiers of the receivers of school i. Each list ends with a 0. An empty list contains a 0 alone in the line.
Output
Your program should write two lines to the standard output. The first line should contain one positive integer: the solution of subtask A. The second line should contain the solution of subtask B.
Sample Input
5
2 4 3 0
4 5 0
0
0
1 0
Sample Output
1
2
对于子任务A,输出入度为零的连通分量数目,对于子任务B,若连通分量数目为1,则输出0,否则输出入度和出度为0的连通分量数目中大的那个
#include<stdio.h>
#include<algorithm>
#include<vector>
#define N 105
using namespace std;
bool in[N];
int s[N],dfn[N],low[N],indegree[N],outdegree[N],f[N];
int ans=0,top=0,num=0;
vector<int> g[N];
void tarjan(int u)
{
int v;
s[++top]=u;
in[u]=true;
dfn[u]=low[u]=++num;
for(int i=0;i<g[u].size();i++)
{
v=g[u][i];
if(!dfn[v])
{
tarjan(v);
if(low[v]<low[u])
low[u]=low[v];
}
else if(in[v] && dfn[v]<low[u])
low[u]=dfn[v];
}
if(dfn[u]==low[u])
{
ans++;
do
{
v=s[top];s[top]=0;top--;
f[v]=ans;
in[v]=false;
}while(v!=u);
}
}
int main()
{
int m,n;
scanf("%d",&n);
int to;
for(int i=1;i<=n;i++)
{
while(1)
{
scanf("%d",&to);
if(to==0)
break;
g[i].push_back(to);
}
}
for(int i=1;i<=n;i++)
{
if(!dfn[i])
{
tarjan(i);
}
}
for(int i=1; i<=n; i++)
{
for(int j=0;j<g[i].size();j++)
{
int v=g[i][j];
if(f[i]!=f[v])
{
outdegree[f[i]]++;
indegree[f[v]]++;
}
}
}
int sum1=0,sum2=0;
for(int i=1;i<=ans;i++)
{
if(!indegree[i])
sum1++;
}
for(int i=1;i<=ans;i++)
{
if(!outdegree[i])
sum2++;
}
printf("%d\n%d\n",sum1,ans==1?0:max(sum1,sum2));
}