Suppose there are N people in ZJU, whose ages are unknown. We have some messages about them. The i-th message shows that the age of person si is not smaller than the age of person ti. Now we need to divide all these N people into several groups. One's age shouldn't be compared with each other in the same group, directly or indirectly. And everyone should be assigned to one and only one group. The task is to calculate the minimum number of groups that meet the requirement.
Input
There are multiple test cases. For each test case: The first line contains two integers N(1≤ N≤ 100000), M(1≤ M≤ 300000), N is the number of people, and M is is the number of messages. Then followed by M lines, each line contain two integers si and ti. There is a blank line between every two cases. Process to the end of input.
Output
For each the case, print the minimum number of groups that meet the requirement one line.
Sample Input
4 4 1 2 1 3 2 4 3 4
Sample Output
3
Hint
set1= {1}, set2= {2, 3}, set3= {4}
Author: LUO, Jiewei
Source: ZOJ Monthly, June 2014
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=112345;
int head[maxn],cnt,dfn[maxn],low[maxn],instack[maxn],Stack[maxn],top,
idx,f[maxn],sum[maxn],deg[maxn],head1[maxn],cnt1,dis[maxn],ans;
struct node{
int to,next;
}e[maxn*3],ee[maxn*3];
void Init(){
memset(head,-1,sizeof(head));
cnt=idx=top=ans=0;
memset(dfn,0,sizeof(dfn));
memset(instack,0,sizeof(instack));
memset(sum,0,sizeof(sum));
memset(deg,0,sizeof(deg));
memset(head1,-1,sizeof(head1));
cnt1=0;
memset(dis,0,sizeof(dis));
}
void add(int u,int v){
e[cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt++;
}
void add1(int u,int v){
ee[cnt1].to=v;
ee[cnt1].next=head1[u];
head1[u]=cnt1++;
}
void tarjan(int u){/*强连通缩点*/
low[u]=dfn[u]=++idx;
instack[u]=1;
Stack[top++]=u;
for(int i=head[u];~i;i=e[i].next){
int v=e[i].to;
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(instack[v])
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u]){
int v;
ans++;
do{
v=Stack[--top];
instack[v]=0;
f[v]=ans;
sum[ans]++;
}while(u!=v);
}
}
int dfs(int x){/*记忆化搜索求最长路*/
if(dis[x])
return dis[x];
int mmax=0;
for(int i=head1[x];~i;i=ee[i].next){
int v=ee[i].to;
mmax=max(mmax,dfs(v));
}
return dis[x]=sum[x]+mmax;
}
int main(){
int n,m,u,v;
while(~scanf("%d%d",&n,&m)){
Init();
while(m--){
scanf("%d%d",&u,&v);
add(u,v);
}
for(int i=1;i<=n;i++)
if(!dfn[i])
tarjan(i);
for(int u=1;u<=n;u++){/*重新建图*/
for(int i=head[u];~i;i=e[i].next){
int v=e[i].to;
if(f[u]!=f[v]){
deg[f[v]]++;
add1(f[u],f[v]);
}
}
}
int Max=-1;
for(int i=1;i<=ans;i++)
if(deg[i]==0)
Max=max(Max,dfs(i));
printf("%d\n",Max);
}
}