旅行计划
题目描述
小明要去一个国家旅游。这个国家有 N N N 个城市,编号为 1 1 1 至 N N N,并且有 M M M 条道路连接着,小明准备从其中一个城市出发,并只往东走到城市 i i i 停止。
所以他就需要选择最先到达的城市,并制定一条路线以城市 i i i 为终点,使得线路上除了第一个城市,每个城市都在路线前一个城市东面,并且满足这个前提下还希望游览的城市尽量多。
现在,你只知道每一条道路所连接的两个城市的相对位置关系,但并不知道所有城市具体的位置。现在对于所有的 i i i,都需要你为小明制定一条路线,并求出以城市 i i i 为终点最多能够游览多少个城市。
输入格式
第一行为两个正整数 N , M N, M N,M。
接下来 M M M 行,每行两个正整数 x , y x, y x,y,表示了有一条连接城市 x x x 与城市 y y y 的道路,保证了城市 x x x 在城市 y y y 西面。
输出格式
N N N 行,第 i i i 行包含一个正整数,表示以第 i i i 个城市为终点最多能游览多少个城市。
样例 #1
样例输入 #1
5 6
1 2
1 3
2 3
2 4
3 4
2 5
样例输出 #1
1
2
3
4
3
提示
均选择从城市 1 1 1 出发可以得到以上答案。
- 对于 20 % 20\% 20% 的数据, 1 ≤ N ≤ 100 1\le N ≤ 100 1≤N≤100;
- 对于 60 % 60\% 60% 的数据, 1 ≤ N ≤ 1000 1\le N ≤ 1000 1≤N≤1000;
- 对于 100 % 100\% 100% 的数据, 1 ≤ N ≤ 100000 1\le N ≤ 100000 1≤N≤100000, 1 ≤ M ≤ 200000 1\le M ≤ 200000 1≤M≤200000。
解析
拓扑排序
#include<bits/stdc++.h>
using namespace std;
//#define int long long
const int N=1e5+5,M=2e5+5,mod=80112002;
int n,m;
int h[N],e[M],ne[M],idx;
int in[N],out[N],cnt[N];
void add(int a,int b){
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void solve(){
scanf("%d%d",&n,&m);
memset(h,-1,sizeof h);
for(int i=1;i<=m;i++){
int x,y;
scanf("%d%d",&x,&y);
add(x,y);
in[y]++;
}
queue<int>q;
for(int i=1;i<=n;i++){
if(in[i]==0) q.push(i);
}
int res=0;
while(q.size()){
int x=q.front();
q.pop();
cnt[x]++;
for(int i=h[x];~i;i=ne[i]){
int j=e[i];
cnt[j]=max(cnt[j],cnt[x]);
if(--in[j]==0) q.push(j);
}
}
for(int i=1;i<=n;i++) printf("%d\n",cnt[i]);
}
signed main(){
int t=1;
// scanf("%lld",&t);
while(t--) solve();
return 0;
}