1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #include<iostream> #include<cstdio> #include<vector> #include<stack> #include<cstring> using namespace std; long long read() { long long x=0,f=1; char c=getchar(); while(!isdigit(c)){if(c=='-') f=-1;c=getchar();} while(isdigit(c)){x=x*10+c-'0';c=getchar();} return x*f; } const int N=100000+100; struct road { int to,IsBack; road (int A,int B) { to=A,IsBack=B; } }; vector <int> e[N]; vector <road> e2[N]; int belong[N],nd_tot,nd_to,low[N],dfn[N],InStack[N],cnt[N]; stack <int> st; void Tarjan(int now) { low[now]=dfn[now]=++nd_to; InStack[now]=true; st.push(now); for(int i=0;i<int(e[now].size());i++) if(dfn[e[now][i]]==0) { Tarjan(e[now][i]); low[now]=min(low[now],low[e[now][i]]); } else if(InStack[e[now][i]]==true) low[now]=min(low[now],low[e[now][i]]); if(low[now]==dfn[now]) { nd_tot++; while(st.empty()==false) { int temp=st.top(); st.pop(); belong[temp]=nd_tot; InStack[temp]=false; cnt[nd_tot]++; if(temp==now) break; } } } int n,m,S,f[N][2]; int dfs(int now,int back) { if(f[now][back]>=0) return f[now][back]; int t_ans=0; bool OK=false; for(int i=0;i<int(e2[now].size());i++) if(e2[now][i].to!=S and back-e2[now][i].IsBack>=0) t_ans=max(t_ans,dfs(e2[now][i].to,back-e2[now][i].IsBack)); else if(back>=e2[now][i].IsBack) OK=true; if(t_ans!=0 or OK==true) return f[now][back]=t_ans+cnt[now]; else return f[now][back]=0; } int main() { n=read(),m=read(); for(int i=1;i<=n;i++) e[i].reserve(4), e2[i].reserve(4); for(int i=1;i<=m;i++) { int s=read(),t=read(); e[s].push_back(t); }
for(int i=1;i<=n;i++) if(dfn[i]==0) Tarjan(i); S=belong[1]; for(int i=1;i<=n;i++) for(int j=0;j<int(e[i].size());j++) if(belong[i]!=belong[e[i][j]]) { e2[belong[i]].push_back(road(belong[e[i][j]],0)); e2[belong[e[i][j]]].push_back(road(belong[i],1)); }
memset(f,0x80,sizeof f); int ans=0; for(int i=0;i<int(e2[S].size());i++) ans=max(ans,dfs(e2[S][i].to,1-e2[S][i].IsBack));
printf("%d",ans+cnt[S]); return 0; }
|