1. 程式人生 > >洛谷——P1137 旅行計劃

洛谷——P1137 旅行計劃

logs 題目 truct www style clu 其中 code ins

https://www.luogu.org/problem/show?pid=1137

題目描述

小明要去一個國家旅遊。這個國家有N個城市,編號為1~N,並且有M條道路連接著,小明準備從其中一個城市出發,並只往東走到城市i停止。

所以他就需要選擇最先到達的城市,並制定一條路線以城市i為終點,使得線路上除了第一個城市,每個城市都在路線前一個城市東面,並且滿足這個前提下還希望遊覽的城市盡量多。

現在,你只知道每一條道路所連接的兩個城市的相對位置關系,但並不知道所有城市具體的位置。現在對於所有的i,都需要你為小明制定一條路線,並求出以城市i為終點最多能夠遊覽多少個城市。

輸入輸出格式

輸入格式:

輸入的第1行為兩個正整數N, M。

接下來M行,每行兩個正整數x, y,表示了有一條連接城市x與城市y的道路,保證了城市x在城市y西面。

輸出格式:

輸出包括N行,第i行包含一個正整數,表示以第i個城市為終點最多能遊覽多少個城市。

輸入輸出樣例

輸入樣例#1:
5 6
1 2
1 3
2 3
2 4
3 4
2 5
輸出樣例#1:
1
2
3
4
3

說明

均選擇從城市1出發可以得到以上答案。

對於20%的數據,N ≤ 100;

對於60%的數據,N ≤ 1000;

對於100%的數據,N ≤ 100000,M ≤ 200000。

拓撲排序練習

 1 #include <algorithm>
 2 #include <cstdio>
 3 #include <queue>
 4 
 5 using namespace std;
 6 
 7 const int N(100000+15);
 8 const int M(200000+15);
 9 int n,m,u,v,rd[N],city_num[N];
10 queue<int>que;
11 
12 int head[N],sumedge;
13 struct Edge
14 {
15     int
v,next; 16 Edge(int v=0,int next=0): 17 v(v),next(next){} 18 }edge[M]; 19 void ins(int u,int v) 20 { 21 edge[++sumedge]=Edge(v,head[u]); 22 head[u]=sumedge; 23 } 24 25 int main() 26 { 27 scanf("%d%d",&n,&m); 28 for(;m--;) 29 { 30 scanf("%d%d",&u,&v); 31 ins(u,v);rd[v]++; 32 } 33 for(int i=1;i<=n;i++) 34 if(!rd[i]) que.push(i),city_num[i]++; 35 for(;!que.empty();) 36 { 37 int fro=que.front();que.pop(); 38 for(int i=head[fro];i;i=edge[i].next) 39 { 40 v=edge[i].v; 41 city_num[v]=max(city_num[v],city_num[fro]+1); 42 if(--rd[v]==0) que.push(v); 43 } 44 } 45 for(int i=1;i<=n;i++) 46 printf("%d\n",city_num[i]); 47 return 0; 48 }

洛谷——P1137 旅行計劃