原题:http://poj.org/problem?id=1236
题意:有n个点,下面n行给出与第i个点相连的结点;在某个点放置软件,那么与该点相连的点也可以得到该软件,问最少要在几个点放置软件;第二问是至少要添加几条边使得该图强连通;
思路:通过强连通求得DAG图,第一问就是求新图中入度 = 0 的点的个数;第二问就是求新图中max ( 入度 = 0 的点个数, 出度 = 0 的点个数 );
注意:如果强连通分量只有一个,那么输出(1\n0\n);
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int maxn = 110;
int n;
int head[maxn], edgenum;
int Stack[maxn], Belong[maxn], DFN[maxn], Low[maxn];
int Time, taj, top;
bool Instack[maxn];
int in[maxn], out[maxn];
struct Edge
{
int from, to;
int next;
}edge[maxn*maxn];
void Tarjan(int u)
{
DFN[u] = Low[u] = ++Time;
Stack[top++] = u;
Instack[u] = true;
for(int i = head[u];i != -1;i = edge[i].next)
{
int v = edge[i].to;
if(DFN[v] == -1)
{
Tarjan(v);
Low[u] = min(Low[u], Low[v]);
}
else
{
if(Instack[v] && Low[u] > DFN[v])
Low[u] = DFN[v];
}
}
if(DFN[u] == Low[u])
{
taj++;
while(1)
{
int now = Stack[--top];
Belong[now] = taj;
Instack[now] = false;
if(now == u) break;
}
}
}
void add(int u, int v)
{
edge[edgenum].from = u;
edge[edgenum].to = v;
edge[edgenum].next = head[u];
head[u] = edgenum++;
}
void init()
{
memset(head, -1, sizeof head);
edgenum = 0;
memset(DFN, -1, sizeof DFN);
memset(Instack, false, sizeof Instack);
Time = taj = top = 0;
}
int main()
{
while(~scanf("%d", &n))
{
init();
for(int i = 1;i<=n;i++)
{
int v;
while(scanf("%d", &v) && v)
{
add(i, v);
}
}
for(int i = 1;i<=n;i++)
{
if(DFN[i] == -1)
Tarjan(i);
}
memset(in, 0, sizeof in);
memset(out, 0, sizeof out);
for(int i = 0;i<edgenum;i++)
{
int u = Belong[edge[i].from];
int v = Belong[edge[i].to];
if(u != v)
{
out[u]++;
in[v]++;
}
}
if(taj == 1)
{
printf("1\n0\n");
continue;
}
int incnt = 0, outcnt = 0;
for(int i = 1;i<=taj;i++)
{
if(in[i] == 0) incnt++;
if(out[i] == 0) outcnt++;
}
printf("%d\n%d\n", incnt, max(incnt, outcnt));
}
return 0;
}