首页 > 代码库 > zoj 3795 Grouping

zoj 3795 Grouping

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 #include <vector> 7 #include <stack> 8 using namespace std; 9 const int maxn=111111;10 vector<int>g[maxn];11 vector<int>to[maxn];12 stack<int>s;13 int n,m;14 int ans;15 int lowlink[maxn],pre[maxn],c[maxn],dp[maxn],sccno[maxn],scc_cnt,dfs_clock;16 void dfs(int u){17     pre[u]=lowlink[u]=++dfs_clock;18     s.push(u);19     for(int i=0;i<g[u].size();i++){20         int v=g[u][i];21         if(!pre[v]){22             dfs(v);23             lowlink[u]=min(lowlink[u],lowlink[v]);24         }25         else if(!sccno[v])lowlink[u]=min(lowlink[u],pre[v]);26     }27     if(lowlink[u]==pre[u]){28         ++scc_cnt;29         while(1){30             int x=s.top();s.pop();31             sccno[x]=scc_cnt;32             ++c[scc_cnt];33             if(x==u)break;34         }35     }36 }37 void find_scc(int n){38     dfs_clock=scc_cnt=0;39     memset(pre,0,sizeof pre);40     memset(sccno,0,sizeof sccno);41     memset(c,0,sizeof c);42     for(int i=1;i<=n;i++)if(!pre[i])dfs(i);43 }44 int DP(int u){45     if(dp[u])return dp[u];46     int res=0;47     for(int i=0;i<to[u].size();i++){48         int v=to[u][i];49         res=max(DP(v),res);50     }51     return dp[u]=res+c[u];52 }53 int main()54 {55 //    freopen("in","r",stdin);56     while(scanf("%d%d",&n,&m)>0){57         for(int i=1;i<=n;i++)g[i].clear();58         while(m--){59             int a,b;60             scanf("%d%d",&a,&b);61             g[a].push_back(b);62         }63         find_scc(n);64         for(int i=1;i<=scc_cnt;i++){65             to[i].clear();66         }67         for(int u=1;u<=n;u++){68             for(int i=0;i<g[u].size();i++){69                 int v=g[u][i];70                 if(sccno[u]!=sccno[v])to[sccno[u]].push_back(sccno[v]);71             }72         }73         memset(dp,0,sizeof dp);74         ans=0;75         for(int i=1;i<=scc_cnt;i++)ans=max(DP(i),ans);76         printf("%d\n",ans);77     }78     return 0;79 }

 

zoj 3795 Grouping