tyvj 1111
//自己模板
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100000;
int V,E;//点数(1) 边数
struct edge//邻接表
{
int t,w;//u->t=w;
int next;
};
int p[maxn];//表头节点
edge G[maxn];
int l;
void init()
{
memset(p,-1,sizeof(p));
l=0;
}
//添加边
void addedge(int u,int t,int w,int l)//u->t=w;
{
G[l].w=w;
G[l].t=t;
G[l].next=p[u];
p[u]=l;
}
//tarjan算法 求有向图强联通分量
int dfn[maxn],lowc[maxn];
//dfn[u]节点u搜索的次序编号,lowc[u]u或者u的子树能够追溯到的栈中的最早的节点
int belg[maxn];//第i个节点属于belg[i]个强连通分量
int stck[maxn],stop;//stck栈
int instck[maxn];//第i个节点是否在栈中
int scnt;//强联通分量
int index;
void dfs(int i)
{
dfn[i]=lowc[i]=++index;
instck[i]=1;//节点i入栈
stck[++stop]=i;
for(int j=p[i];j!=-1;j=G[j].next)
{
int t=G[j].t;
//更新lowc数组
if(!dfn[t])//t没有遍历过
{
dfs(t);
if(lowc[i]>lowc[t]) lowc[i]=lowc[t];
}//t是i的祖先节点
else if(instck[t]&&lowc[i]>dfn[t]) lowc[i]=dfn[t];
}
//是强连通分量的根节点
if(dfn[i]==lowc[i])
{
scnt++;
int t;
do
{
t=stck[stop--];
instck[t]=0;
belg[t]=scnt;
}while(t!=i);
}
}
int tarjan()
{
stop=scnt=index=0;
memset(dfn,0,sizeof(dfn));
memset(instck,0,sizeof(instck));
for(int i=1;i<=V;i++)
{
if(!dfn[i]) dfs(i);
}
return scnt;
}
int main()
{
while(scanf("%d",&V)==1)
{
init();
for(int i=1;i<=V;i++)
{
int x;
while(scanf("%d",&x)==1&&x)
{
E++;
addedge(i,x,1,l++);
}
}
int ans=tarjan();
printf("%d/n",ans);
}
return 0;
}
//吉大模板 邻接表版
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100000;
int V,E;//点数(1) 边数
struct edge//邻接表
{
int t,w;//u->t=w;
int next;
};
int p[maxn];//表头节点
edge G[maxn];
int l;
void init()
{
memset(p,-1,sizeof(p));
l=0;
}
//添加边
void addedge(int u,int t,int w,int l)//u->t=w;
{
G[l].w=w;
G[l].t=t;
G[l].next=p[u];
p[u]=l;
}
//tarjan算法 求有向图强联通分量
int dfn[maxn],lowc[maxn];
//dfn[u]节点u搜索的次序编号,lowc[u]u或者u的子树能够追溯到的栈中的最早的节点
int stck[maxn],stop;//stck栈
int pre[maxn];//
int scnt;//强联通分量
int cnt;//
void dfs(int v)//1-V
{
int t,minc=lowc[v]=pre[v]=cnt++;
stck[stop++]=v;
for(int i=p[v];i!=-1;i=G[i].next)
{
int pv=G[i].t;
if(pre[pv]==-1) dfs(pv);
if(lowc[pv]<minc) minc=lowc[pv];
}
if(minc<lowc[v])
{
lowc[v]=minc;
return ;
}
do
{
dfn[t=stck[--stop]]=scnt;
lowc[t]=V;
}while(t!=v);
++scnt;
}
int tarjan()
{
stop=cnt=scnt=0;
memset(pre,-1,sizeof(pre));
for(int i=1;i<=V;i++)
{
if(pre[i]==-1) dfs(i);
}
return scnt;
}
int main()
{
while(scanf("%d",&V)==1)
{
init();
for(int i=1;i<=V;i++)
{
int x;
while(scanf("%d",&x)==1&&x)
{
E++;
addedge(i,x,1,l++);
}
}
int ans=tarjan();
printf("%d/n",ans);
}
return 0;
}