您的位置:首页 > 其它

ZOJ 3795 Grouping

2015-05-02 10:45 441 查看

Grouping

Time Limit: 2000ms
Memory Limit: 65536KB
This problem will be judged on ZJU. Original ID: 3795
64-bit integer IO format: %lld Java class name: Main

Suppose there are N people in ZJU, whose ages are unknown. We have some messages about them. Thei-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 Mlines, 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}

Source

ZOJ Monthly, June 2014

Author

LUO, Jiewei

解题:tarjan缩点+DAG最长路

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct arc{
int to,next;
arc(int x = 0,int y = -1){
to = x;
next = y;
}
}e[500000];
int head[maxn],dfn[maxn],low[maxn],belong[maxn],num[maxn];
bool instack[maxn];
int tot,idx,scc,n,m,dp[maxn];
stack<int>stk;
vector<int>g[maxn];
void add(int u,int v){
e[tot] = arc(v,head[u]);
head[u] = tot++;
}
void init(){
for(int i = 0; i < maxn; ++i){
dp[i] = head[i] = -1;
dfn[i] = low[i] = 0;
belong[i] = num[i] = 0;
instack[i] = false;
g[i].clear();
}
idx = scc = tot = 0;
while(!stk.empty()) stk.pop();
}
void tarjan(int u){
dfn[u] = low[u] = ++idx;
instack[u] = true;
stk.push(u);
for(int i = head[u]; ~i; i = e[i].next){
if(!dfn[e[i].to]){
tarjan(e[i].to);
low[u] = min(low[u],low[e[i].to]);
}else if(instack[e[i].to]) low[u] = min(low[u],dfn[e[i].to]);
}
if(low[u] == dfn[u]){
scc++;
int v;
do{
instack[v = stk.top()] = false;
belong[v] = scc;
num[scc]++;
stk.pop();
}while(v != u);
}
}
int dfs(int u){
if(dp[u] != -1) return dp[u];
dp[u] = num[u];
for(int i = g[u].size()-1; i >= 0; --i)
dp[u] = max(dp[u],num[u] + dfs(g[u][i]));
return dp[u];
}
int main(){
int u,v;
while(~scanf("%d %d",&n,&m)){
init();
for(int i = 0; i < m; ++i){
scanf("%d %d",&u,&v);
add(u,v);
}
for(int i = 1; i <= n; ++i)
if(!dfn[i]) tarjan(i);
for(int i = 1; i <= n; ++i){
for(int j = head[i]; ~j; j = e[j].next){
if(belong[i] != belong[e[j].to])
g[belong[e[j].to]].push_back(belong[i]);
}
}
int ret = 0;
for(int i = 1; i <= scc; ++i)
ret = max(ret,dfs(i));
printf("%d\n",ret);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: