思路:很显然找最大链
方法:先缩点形成一张DAG,再跑一遍拓扑dp找链的最大值(感觉思路很清晰~
Code
#include<bits/stdc++.h>
#define re register
#define ll long long
#define inl inline
using namespace std;
const int N=2e6+10;
int read(){
int sum=0,f=1;char c=getchar();
while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}
while(isdigit(c)){sum=(sum<<3)+(sum<<1)+(c^48);c=getchar();}
return sum*f;
}
int n,m,cnt,head[N],dfn[N],low[N],top,color,dep,col[N],g[N],stk[N],ans,cnt2,dis[N],head2[N];
int scc[N];
struct node{
int to,nxt;
}e[N],r[N];
void add(int u,int v){
e[++cnt].to=v;
e[cnt].nxt=head[u];
head[u]=cnt;
}
void add2(int u,int v){
r[++cnt2].to=v;
r[cnt2].nxt=head2[u];
head2[u]=cnt2;
}
inl void tarjan(int u){
dfn[u]=low[u]=++dep,stk[++top]=u;
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].to;
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(!col[v]) low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u]){
color++;
col[u]=color;
scc[color]++;
while(stk[top]!=u){
col[stk[top--]]=color;
scc[color]++;
}
top--;
}
}
int u[N],y[N],ind[N];
queue<int> q;
int main(){
n=read(),m=read();
for(int i=1;i<=m;i++){
u[i]=read(),y[i]=read();
add(u[i],y[i]);
}
for(int i=1;i<=n;i++){if(!dfn[i]) tarjan(i);}
for(re int i=1;i<=m;i++){
if(col[u[i]]!=col[y[i]]){
add2(col[u[i]],col[y[i]]);
ind[col[y[i]]]++;
}
}
for(re int i=1;i<=color;i++){
if(!ind[i]) q.push(i),dis[i]=scc[i],ans=max(dis[i],ans);
}
while(q.size()){
int tmp=q.front();q.pop();
for(re int i=head2[tmp];i;i=r[i].nxt){
int w=r[i].to;
dis[w]=max(dis[w],dis[tmp]+scc[w]);
ans=max(ans,dis[w]);
ind[w]--;
if(!ind[w]) q.push(w);
}
}
printf("%d\n",ans);
return 0;
}