poj2553
题意的关键是Here are some new definitions. A node v in a graph G=(V,E) is called a sink, if for every node w in G that is reachable from v, v is also reachable from w.,就是叫你求出度为0的强连通分量的元素。
话说这题的数据太水了,我的tarjan有bug还能过。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct edge
{
int v,nxt;
}e[5000*5000+10];
int head[5005],dfn[5005],low[5005],vis[5005],sta[5005],belong[5005],cd[5005];
int index,top,n,m,cnt;
void tarjan(int u)
{
int v;
dfn[u]=low[u]=++index;
sta[top++]=u;
vis[u]=1;
for(int i=head[u];i!=-1;i=e[i].nxt)
{
v=e[i].v;
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])
{
cnt++;
do
{
v=sta[--top];
belong[v]=cnt;
vis[v]=0;
}while(v!=u);
}
}
int main()
{
std::ios::sync_with_stdio(false);
while(cin>>n)
{
if(!n) break;
cin>>m;
for(int i=1;i<=n;i++)
{
head[i]=-1;
dfn[i]=0;
low[i]=0;
vis[i]=0;
cd[i]=0;
// belong[i]=0;
}
cnt=0;
index=0;
top=0;
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v;
e[i].v=v;
e[i].nxt=head[u];
head[u]=i;
}
for(int i=1;i<=n;i++)
if(!dfn[i])
tarjan(i);
for(int i=1;i<=n;i++)
for(int j=head[i];j!=-1;j=e[j].nxt)
{
int u=i,v=e[j].v;
if(belong[u]!=belong[v])
{
cd[belong[u]]++;
}
}
for(int i=1;i<=n;i++)
if(cd[belong[i]]==0)
cout<<i<<" ";
// cout<<endl;
// cout<<"连通分量的个数:"<<cnt<<endl;
//cout<<"每个点对应的连通分量:";
//for(int i=1;i<=n;i++)
// // cout<<belong[i]<<" ";
// cout<<endl;
// cout<<"每个点对应的连通分量的出度:";
// for(int i=1;i<=n;i++)
// cout<<cd[belong[i]]<<" ";
// cout<<endl;
cout<<endl;
}
return 0;
}