#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
#include<vector>
#include<stack>
#include<list>
#include<map>
#include<set>
#define P pair<int ,int >
using namespace std;
const int maxn = 100000+5;
int Laxt[maxn],cnt,n,m,ans;
int times,dfn[maxn],low[maxn],scc[maxn],scc_cnt,sccnum[maxn],in[maxn],dis[maxn];
int stc[maxn],top,instc[maxn];
map<P,int> mp;
struct node
{
int from;
int to;
int next;
int w;
} edge[maxn*20],e[maxn*20] ;
void add(int u,int v,int w)
{
edge[++cnt].from=u;
edge[cnt].next=Laxt[u];
Laxt[u]=cnt;
edge[cnt].to=v;
edge[cnt].w=w;
}
int dfs(int u)
{
dfn[u]=low[u]=++times;
stc[++top]=u;
instc[u]=1;
for(int i=Laxt[u]; i; i=edge[i].next)
{
int v=edge[i].to;
if(!dfn[v])
{
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(instc[v])
{
low[u]=min(low[u],low[v]);
}
}
if(dfn[u]==low[u])
{
scc_cnt++;
while(true)
{
int x=stc[top--];
scc[x]=scc_cnt;
sccnum[scc_cnt]++;
instc[x]=0;
if(x==u) break;
}
}
}
queue<int> q;
void tarjan()
{
for(int i=1; i<=n; i++)
if(!dfn[i]) dfs(i);
for(int i=1; i<=cnt; i++)
{
e[i]=edge[i];
}
memset(Laxt,0,sizeof(Laxt));
for(int i=1; i<=cnt; i++)
{
if(scc[e[i].from]!=scc[e[i].to]&&!mp[make_pair(scc[e[i].from],scc[e[i].to])])
{
in[scc[e[i].to]]++;
mp[make_pair(scc[e[i].from],scc[e[i].to])]=1;
add(scc[e[i].from],scc[e[i].to],1);
}
}
for(int i=1; i<=scc_cnt; i++)
{
if(in[i]==0)
{
q.push(i);
dis[i]=sccnum[i];
}
else
{
dis[i]=0;
}
}
}
void topsort()
{
int now;
while(!q.empty())
{
now=q.front();
q.pop();
for(int j=Laxt[now]; j; j=edge[j].next)
{
in[edge[j].to]--;
if(in[edge[j].to]==0)q.push(edge[j].to);
if(dis[now]+sccnum[edge[j].to]>dis[edge[j].to])
{
dis[edge[j].to]=dis[now]+sccnum[edge[j].to];
}
}
}
}
int main()
{
scanf("%d %d",&n,&m);
int a,b;
for(int i=1; i<=m; i++)
{
scanf("%d %d",&a,&b);
add(a,b,1);
}
tarjan();
topsort();
int maxnode=0;
for(int i=1; i<=n; i++)
{
if(maxnode<dis[i])
{
maxnode=dis[i];
}
}
printf("%d\n",maxnode);
}
点击打开链接
Problem F. A-maze-ing
最新推荐文章于 2019-07-07 20:43:04 发布