题意:在一个有向图中,求出 点v能到达的点都能到达v的一个子图,然后把里面的点从小到大输出,没有的话输出空行。
思路:题意很明显,求出强连通分量,缩点后,找出出度为0的点然后保存里面的点。
//484K 94MS
#include
#include
#include
using namespace std;
const int VM = 5005;
const int EM = VM*10;
struct Edge
{
int to,nxt;
}edge[EM];
int head[VM],vis[VM],stack[VM+100],dfn[VM],belong[VM],low[VM];
int cnt,ep,scc,top;
int min (int a, int b)
{
return a > b ? b : a;
}
void addedge (int cu,int cv)
{
edge[ep].to = cv;
edge[ep].nxt = head[cu];
head[cu] = ep ++;
}
void Tarjan(int u)//Tarjan求强连通分量
{
int v;
dfn[u] = low[u] = ++cnt;
stack[top ++] = u;
vis[u] = 1;
for (int i = head[u];i != -1;i = edge[i].nxt)
{
v = edge[i].to;
if (!dfn[v])
{
Tarjan (v);
low[u] = min(low[u],low[v]);
}
else if (vis[v]) low[u] = min(low[u],dfn[v]);
}
if (dfn[u] == low[u])
{
++scc ;
do{
v = stack[--top];
vis[v] = 0;
belong[v] = scc;
}while (u != v);
}
}
void solve(int n)
{
scc = top = cnt = 0;
int u,v;
memset (vis,0,sizeof(vis));
memset (dfn,0,sizeof(dfn));
for (u = 1;u <= n;u ++)
if (!dfn[u])
Tarjan(u);
int outdeg[VM];
memset (outdeg,0,sizeof(outdeg));
for (u = 1;u <= n;u ++) //算出缩点后没个强连通分量的出度
{
for (int i = head[u];i != -1;i = edge[i].nxt)
{
v = edge[i].to;
if (belong[u] != belong[v])
outdeg[belong[u]] ++;
}
}
cnt = 0;
int m = 0;
int node[VM];
for (u = 1;u <= scc;u ++)
if (outdeg[u] == 0)
{
cnt ++;
for (v = 1;v <= n;v ++)
if (belong[v] == u)
node[m ++] = v;
}
if (!cnt)
{
printf ("\n");
return ;
}
sort (node,node + m);
for (int i = 0;i < m-1;i ++)
printf ("%d ",node[i]);
printf ("%d",node[m-1]);
printf ("\n");
}
int main ()
{
int n,m,u,v;
while (~scanf ("%d",&n)&&n)
{
scanf ("%d",&m);
memset (head,-1,sizeof(head));
ep = 0;
while (m --)
{
scanf ("%d%d",&u,&v);
addedge (u,v);
}
solve(n);
}
return 0;
}